### Get Problem Count
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
An example function demonstrating how to use the `ajaxReq` and `allPbPostData` to get the total number of problems available on LeetCode.
```APIDOC
## Get Problem Count (`getpbCnt`)
### Description
This function retrieves the total number of problems available in the LeetCode problem set by querying the `problemsetQuestionListV2` endpoint with a limit of 0.
### Method
POST
### Endpoint
`https://leetcode.cn/graphql/`
### Parameters
None directly, but it utilizes `allPbPostData(0, 0)` to set up the request.
### Request Example (Conceptual)
```javascript
let headers = { 'Content-Type': 'application/json' };
ajaxReq('POST', lcgraphql, headers, allPbPostData(0, 0), res => {
// Process response
});
```
### Response
#### Success Response (200)
Returns the total number of problems as an integer.
#### Response Example
```javascript
// Assuming the ajaxReq callback is executed
// The total number of problems is extracted from the response
// For example, if res.data.problemsetQuestionListV2.totalLength is 3500, the function returns 3500.
3500
```
```
--------------------------------
### LeetCodeRating GM Menu Configuration System
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code defines the configuration options for the LeetCodeRating extension, managed through Tampermonkey's menu commands. It includes an array `menu_ALL` where each element represents a feature with its key, display name, description, default state, and a flag for whether it's a 'pb function'. The code also demonstrates how to read (`GM_getValue`) and set (`GM_setValue`) configuration values, and how to register custom menu commands (`GM_registerMenuCommand`) to toggle these features.
```javascript
// 菜单配置项定义
let menu_ALL = [
['switchvpn', 'vpn', '是否使用cdn访问数据', false, false],
['switchupdate', 'switchupdate', '是否每天最多只更新一次', true, true],
['switchcopyright', 'pb function', '题解复制去除版权信息', true, true],
['switchTea', '0x3f tea', '题库页灵茶信息显示', true, true],
['switchpbRepo', 'pbRepo function', '题库页周赛难度评分(不包括灵茶)', true, false],
['switchpbscore', 'pb function', '题目页周赛难度评分', true, true],
['switchpbside', 'switchpbside function', '题目页侧边栏分数显示', true, true],
['switchpbsearch', 'switchpbsearch function', '题目页题目搜索框', true, true],
['switchsearch', 'search function', '题目搜索页周赛难度评分', true, false],
['switchpblist', 'pbList function', '题单页周赛难度评分', true, false],
['switchstudy', 'studyplan function', '学习计划周赛难度评分', true, false],
['switchlevel', 'level function', '算术评级显示', true, false],
['switchrealoj', 'delvip function', '模拟oj环境(去除难度等信息)', false, true],
['switchdark', 'dark function', '自动切换白天黑夜模式', false, true],
['switchpbstatus', 'pbstatus function', '讨论区显示题目完成状态', true, true],
['switchperson', 'person function', '纸片人', false, true]
];
// 读取和设置菜单值
GM_getValue('switchpbscore'); // 读取配置
GM_setValue('switchpbscore', true); // 设置配置
// 注册菜单命令
GM_registerMenuCommand('✅ 题目页周赛难度评分', function() {
menu_switch('switchpbscore', 'pb function', '题目页周赛难度评分', 'true');
});
```
--------------------------------
### LeetCodeRating Data Fetching Configuration and Logic
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code configures the data source URLs for LeetCodeRating, allowing users to choose between GitHub's native URLs (requiring a VPN) and CDN mirror URLs for better accessibility in certain regions. It dynamically sets `rakingUrl`, `levelUrl`, and `versionUrl` based on the `switchvpn` setting. The `getScore` function handles fetching the weekly contest rating data, including logic to update the data only once per day and store it locally using `GM_setValue` for performance.
```javascript
// 数据源URL配置
let isVpn = !GM_getValue('switchvpn');
let rakingUrl, levelUrl, versionUrl;
if (isVpn) {
// GitHub 原生地址(需科学上网)
rakingUrl = 'https://zerotrac.github.io/leetcode_problem_rating/data.json';
levelUrl = 'https://raw.githubusercontent.com/zhang-wangz/LeetCodeRating/main/stormlevel/data.json';
versionUrl = 'https://raw.githubusercontent.com/zhang-wangz/LeetCodeRating/main/version.json';
} else {
// CDN 镜像地址(国内可用)
rakingUrl = 'https://raw.gitmirror.com/zerotrac/leetcode_problem_rating/main/data.json';
levelUrl = 'https://raw.gitmirror.com/zhang-wangz/LeetCodeRating/main/stormlevel/data.json';
versionUrl = 'https://raw.gitmirror.com/zhang-wangz/LeetCodeRating/main/version.json';
}
// 获取周赛分数数据
async function getScore() {
let now = getCurrentDate(1);
let preDate = GM_getValue('preDate', '');
// 每天只更新一次数据
if (t2rate[t2rateVersion] == null || preDate == '' || preDate != now) {
let res = await new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'get',
url: rakingUrl + '?timeStamp=' + new Date().getTime(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
onload: function(res) { resolve(res); },
onerror: function(err) { console.log('error', err); }
});
});
if (res.status === 200) {
t2rate = {};
pbName2Id = {};
let json = JSON.parse(res.response);
for (const element of json) {
t2rate[element.ID] = element;
// 四舍五入取整
t2rate[element.ID]['Rating'] = Number.parseInt(
Number.parseFloat(element['Rating']) + 0.5
);
pbName2Id[element.TitleZH] = element.ID;
}
GM_setValue('t2ratedb', JSON.stringify(t2rate));
GM_setValue('pbName2Id', JSON.stringify(pbName2Id));
GM_setValue('preDate', now);
}
}
}
```
--------------------------------
### Illustrate Arithmetic Rating Data Format in JSON
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Shows the JSON structure for arithmetic rating data as found in `stormlevel/data.json`. Each entry includes an ID, Title (English and Chinese), Level, and Difficulty.
```json
{
"ID": "1",
"Title": "Two Sum",
"TitleCn": "两数之和",
"Level": 2,
"Difficulty": "Easy"
}
```
--------------------------------
### Fetch LeetCode Problem Data via GraphQL API (JavaScript)
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This snippet demonstrates how to interact with the LeetCode GraphQL API to fetch problem information. It defines API endpoints, a generic AJAX request function, and a specific function to retrieve a list of problems with their metadata. The `allPbPostData` function constructs the GraphQL query and variables for fetching problem lists, while `getpbCnt` specifically retrieves the total number of problems.
```javascript
const lcgraphql = 'https://leetcode.cn/graphql/';
const lcnojgo = 'https://leetcode.cn/graphql/noj-go/';
const ajaxReq = (type, reqUrl, headers, data, successFuc, asyn = false) => {
return $.ajax({
type: type,
contentType: 'application/json;charset=UTF-8',
url: reqUrl,
data: data != null ? JSON.stringify(data) : null,
async: asyn,
xhrFields: { withCredentials: true },
headers: headers,
success: function(result) { successFuc(result); },
error: function(e) { console.log(e.status, e.responseText); }
});
};
function allPbPostData(skip, limit) {
return {
query: `
query problemsetQuestionListV2($filters: QuestionFilterInput, $limit: Int, $skip: Int) {
problemsetQuestionListV2(filters: $filters, limit: $limit, skip: $skip) {
questions {
id
titleSlug
title
translatedTitle
questionFrontendId
paidOnly
difficulty
status
acRate
}
totalLength
hasMore
}
}
`,
variables: {
categorySlug: 'all-code-essentials',
skip: skip,
limit: limit,
filters: {}
},
operationName: 'problemsetQuestionListV2'
};
}
function getpbCnt() {
let total = 0;
let headers = { 'Content-Type': 'application/json' };
ajaxReq('POST', lcgraphql, headers, allPbPostData(0, 0), res => {
total = res.data.problemsetQuestionListV2.totalLength;
});
return total; // 返回题目总数,如 3500+
}
```
--------------------------------
### Problem Repository Page Rendering
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Handles the dynamic rendering and modification of the problem repository page, including replacing difficulty labels with contest ratings and adding links to contest collections.
```APIDOC
## Problem Repository Page Rendering (`getData`)
### Description
This function modifies the LeetCode problem repository page. It can inject links to external problem collections (like '灵茶题集') and replace the default difficulty tags with contest-based ratings fetched from `t2rate`.
### Method
Client-side JavaScript execution
### Endpoint
Applies to the LeetCode problem repository page URL.
### Parameters
None directly, but relies on `GM_getValue` for user preferences and `t2rate` for rating data.
#### Local Storage / User Preferences
- `switchpbRepo` (boolean): Enables/disables replacing difficulty tags.
- `switchTea` (boolean): Enables/disables the '灵茶题集' link.
- `switchlevel` (boolean): Enables/disables displaying '算术评级'.
- `t2ratedb` (string): JSON string of rating data, parsed into `t2rate` object.
### Request Example (Conceptual)
```javascript
// This function is typically called when the page loads or is updated.
getData();
```
### Response
Modifies the DOM of the problem repository page in-place. No direct JSON response.
#### Success Response (DOM Modification)
- Difficulty tags are replaced with numerical ratings from `t2rate`.
- '灵茶题集' link is added if `switchTea` is enabled.
- '算术评级' is displayed if `switchlevel` is enabled and data exists.
#### Response Example (DOM Change)
Before:
```html
中等
```
After (if `t2rate` has data for the problem ID):
```html
1850
```
```
--------------------------------
### Fetch Problem List Data
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Provides the GraphQL query and variables structure to fetch a list of problems from LeetCode, including details like title, difficulty, and acceptance rate.
```APIDOC
## Fetch Problem List Data (`problemsetQuestionListV2`)
### Description
This function constructs the payload for a GraphQL query to retrieve a paginated list of problems from the LeetCode problem set. It allows filtering and pagination.
### Method
POST
### Endpoint
`https://leetcode.cn/graphql/`
### Parameters
#### Query Parameters
None
#### Request Body
- `query` (string): The GraphQL query string for `problemsetQuestionListV2`.
- `variables` (object): Variables for the query.
- `categorySlug` (string): The category of problems (e.g., 'all-code-essentials').
- `skip` (integer): The number of problems to skip for pagination.
- `limit` (integer): The maximum number of problems to return.
- `filters` (object): An object for filtering problems (currently an empty object).
- `operationName` (string): The name of the operation, which is `problemsetQuestionListV2`.
### Request Example
```json
{
"query": "\n query problemsetQuestionListV2($filters: QuestionFilterInput, $limit: Int, $skip: Int) {\n problemsetQuestionListV2(filters: $filters, limit: $limit, skip: $skip) {\n questions {\n id\n titleSlug\n title\n translatedTitle\n questionFrontendId\n paidOnly\n difficulty\n status\n acRate\n }\n totalLength\n hasMore\n }\n }
",
"variables": {
"categorySlug": "all-code-essentials",
"skip": 0,
"limit": 10,
"filters": {}
},
"operationName": "problemsetQuestionListV2"
}
```
### Response
#### Success Response (200)
- `data` (object): The data returned from the GraphQL query.
- `problemsetQuestionListV2` (object): Contains the list of questions and pagination info.
- `questions` (array): An array of problem objects.
- `id` (string): The unique ID of the problem.
- `titleSlug` (string): The slug for the problem title.
- `title` (string): The original title of the problem.
- `translatedTitle` (string): The translated title of the problem.
- `questionFrontendId` (string): The frontend ID of the problem.
- `paidOnly` (boolean): Indicates if the problem is for premium users.
- `difficulty` (string): The difficulty level (e.g., 'Easy', 'Medium', 'Hard').
- `status` (string): The user's status for this problem (e.g., 'AC', 'NotStarted').
- `acRate` (number): The acceptance rate of the problem.
- `totalLength` (integer): The total number of problems available.
- `hasMore` (boolean): Indicates if there are more problems available.
#### Response Example
```json
{
"data": {
"problemsetQuestionListV2": {
"questions": [
{
"id": "1",
"titleSlug": "two-sum",
"title": "Two Sum",
"translatedTitle": "两数之和",
"questionFrontendId": "1",
"paidOnly": false,
"difficulty": "Easy",
"status": null,
"acRate": 0.54321
}
],
"totalLength": 3500,
"hasMore": true
}
}
}
```
```
--------------------------------
### Problem Detail Page Rendering
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Enhances the problem detail page by displaying contest-specific ratings, links to the contest, and the problem's index within that contest.
```APIDOC
## Problem Detail Page Rendering (`getpb`)
### Description
This function customizes the LeetCode problem detail page. It replaces the standard difficulty display with a contest rating if available and adds contextual information such as the contest name and the problem's index within that contest.
### Method
Client-side JavaScript execution
### Endpoint
Applies to individual LeetCode problem detail page URLs.
### Parameters
None directly, but relies on `GM_getValue` for user preferences and `t2rate` for rating data.
#### Local Storage / User Preferences
- `switchrealoj` (boolean): Potentially related to another feature, not fully detailed here.
- `switchpbscore` (boolean): Enables/disables displaying the contest rating on the problem page.
- `t2ratedb` (string): JSON string of rating data, parsed into `t2rate` object.
### Request Example (Conceptual)
```javascript
// This function is typically called when a problem detail page loads.
getpb();
```
### Response
Modifies the DOM of the problem detail page in-place. No direct JSON response.
#### Success Response (DOM Modification)
- The difficulty tag is replaced with a numerical rating from `t2rate` if `switchpbscore` is enabled.
- A link to the specific contest is created, displaying the contest name and linking to the contest page.
- The problem's index within the contest (e.g., 'Q3') is displayed.
- '算术评级' is displayed if available.
#### Response Example (DOM Change)
Before:
```html
中等
```
After (if `t2rate` has data for the problem ID and `switchpbscore` is true):
```html
1850第 250 场周赛Q3算术评级: 7
```
```
--------------------------------
### Add LeetCode Problem Search Box with JavaScript and Layui
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Implements a search box in the navigation bar to find LeetCode problems by number or keyword. It utilizes the Layui library for dropdown functionality and debounces input to efficiently search problems via an AJAX POST request.
```javascript
function createSearchBtn() {
if (!GM_getValue('switchpbsearch')) return;
if (document.querySelector('#id-dropdown') != null) return;
const div = document.createElement('div');
div.setAttribute('class', 'layui-inline leetcodeRating-search');
div.innerHTML = ``;
const logo = document.querySelector('nav > div > ul');
logo.insertAdjacentElement('afterend', div);
layui.use(function() {
let dropdown = layui.dropdown;
let $ = layui.$;
let inst = dropdown.render({
elem: '#id-dropdown',
data: [],
click: function(obj) {
this.elem.val(obj.title);
this.elem.attr('data-id', obj.id);
}
});
$(inst.config.elem).on('input', function() {
let value = $(this).val().trim();
let dataNew = searchProblems(value);
dropdown.reloadData(inst.config.id, { data: dataNew });
});
});
}
function searchProblems(search) {
let queryT = `
query problemsetQuestions($in: ProblemsetQuestionsInput!) {
problemsetQuestions(in: $in) {
questions {
titleCn
titleSlug
frontendId
difficulty
}
}
}
`;
let list = {
query: queryT,
operationName: 'problemsetQuestions',
variables: { in: { query: search, limit: 10, offset: 0 } }
};
let resLst = [];
$.ajax({
type: 'POST',
url: lcnojgo,
data: JSON.stringify(list),
success: function(res) {
let data = res.data.problemsetQuestions.questions;
for (let idx = 0; idx < data.length; idx++) {
let resp = data[idx];
resLst.push({
id: idx,
title: resp.frontendId + '.' + resp.titleCn,
href: 'https://leetcode.cn/problems/' + resp.titleSlug,
target: '_self'
});
}
},
async: false,
xhrFields: { withCredentials: true },
contentType: 'application/json;charset=UTF-8'
});
return resLst;
}
```
--------------------------------
### Synchronize LeetCode Problem Status with JavaScript
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Synchronizes user's LeetCode problem-solving status by fetching data from the LeetCode API and storing it. This data is then used to display problem completion icons on discussion pages. It handles pagination and updates a local storage value.
```javascript
let pbstatus = JSON.parse(GM_getValue('pbstatus', '{}').toString());
async function syncAllProblemStatus() {
const cnt = Math.ceil(getpbCnt() / 100);
const headers = { 'Content-Type': 'application/json' };
const promises = [];
for (let i = 0; i < cnt; i++) {
promises.push(
ajaxReq('POST', lcgraphql, headers, allPbPostData(i * 100, 100), async res => {
const questions = res.data.problemsetQuestionListV2.questions;
for (const pb of questions) {
pbstatus[pb.titleSlug] = {
titleSlug: pb.titleSlug,
id: pb.questionFrontendId,
status: pb.status, // 'SOLVED' | 'ATTEMPTED' | null
title: pb.title,
titleCn: pb.translatedTitle,
difficulty: pb.difficulty,
paidOnly: pb.paidOnly
};
}
}, true)
);
}
await Promise.all(promises);
GM_setValue('pbstatus', JSON.stringify(pbstatus));
}
function getPbstatusIcon(code, score, paid) {
let value;
switch (code) {
case 1: // AC 已通过
value = ``;
break;
case 2: // ATTEMPTED 尝试过但未通过
value = ``;
break;
case 3: // TO_DO 未做
value = ``;
break;
}
if (GM_getValue('switchpbstatusscoredefault')) {
if (score) value += ` [难度分 ${score}] `;
if (paid) value += ` (会员题) `;
}
return value;
}
function handleLink(link) {
let [status, score, paid] = getpbRelation(link.href);
if (!status) return;
let code = status == 'TO_DO' ? 3 : status == 'SOLVED' ? 1 : 2;
let iconStr = getPbstatusIcon(code, score, paid);
let iconEle = document.createElement('span');
iconEle.innerHTML = iconStr;
link.parentNode.insertBefore(iconEle, link);
link.setAttribute('linkId', 'leetcodeRating');
}
```
--------------------------------
### LeetCode GraphQL API Endpoints
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Defines the base URLs for the LeetCode GraphQL API and provides a utility function for making AJAX requests.
```APIDOC
## LeetCode GraphQL API Endpoints
### Description
This section details the GraphQL API endpoints for LeetCode and a generic AJAX request function to interact with them.
### Endpoints
- `https://leetcode.cn/graphql/`
- `https://leetcode.cn/graphql/noj-go/`
### Utility Function: `ajaxReq`
#### Description
A generic function to perform AJAX requests to the LeetCode GraphQL API.
#### Parameters
- `type` (string): The HTTP method (e.g., 'POST', 'GET').
- `reqUrl` (string): The URL of the API endpoint.
- `headers` (object): An object containing request headers.
- `data` (object): The data payload for the request (will be JSON stringified).
- `successFuc` (function): A callback function to handle successful responses.
- `asyn` (boolean, optional): Whether the request should be asynchronous (defaults to `false`).
### Request Example (Conceptual)
```javascript
const lcgraphql = 'https://leetcode.cn/graphql/';
const ajaxReq = (type, reqUrl, headers, data, successFuc, asyn = false) => {
return $.ajax({
type: type,
contentType: 'application/json;charset=UTF-8',
url: reqUrl,
data: data != null ? JSON.stringify(data) : null,
async: asyn,
xhrFields: { withCredentials: true },
headers: headers,
success: function(result) { successFuc(result); },
error: function(e) { console.log(e.status, e.responseText); }
});
};
```
```
--------------------------------
### UserScript Metadata for LeetCodeRating
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This UserScript metadata block is essential for Tampermonkey to identify and manage the LeetCodeRating extension. It specifies the script's name, version, author, and importantly, the `@match` directive to ensure it runs on LeetCode domains. It also declares necessary GM_* grants for accessing browser storage, making network requests, and adding styles, along with requiring jQuery and Layui libraries.
```javascript
// ==UserScript==
// @name LeetCodeRating|显示力扣周赛难度分
// @namespace https://github.com/zhang-wangz
// @version 3.1.1
// @license MIT
// @description LeetCodeRating 力扣周赛分数显现和相关力扣小功能
// @author 小东是个阳光蛋(力扣名)
// @match *://*leetcode.cn/*
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addStyle
// @require https://unpkg.com/jquery@3.5.1/dist/jquery.min.js
// @require https://unpkg.com/layui@2.9.6/dist/layui.js
// ==/UserScript==
```
--------------------------------
### URL Change Listener and Page Refresh for LeetCode SPA
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code listens for URL changes in LeetCode's single-page application to ensure that plugin functionalities work across different pages. It overrides `history.pushState` and `history.replaceState` to dispatch a custom 'urlchange' event, which is then used to trigger re-initialization of page-specific functions.
```javascript
// 页面 URL 匹配规则
const allUrl = 'https://leetcode.cn/problemset/.*'; // 题库页
const pblistUrl = 'https://leetcode.cn/problem-list/.*'; // 题单页
const pbUrl = 'https://leetcode.{2,7}/problems/.*'; // 题目页
const searchUrl = 'https://leetcode.cn/search/.*'; // 搜索页
const studyUrl = 'https://leetcode.cn/studyplan/.*'; // 学习计划页
const discussUrl = 'https://leetcode.cn/discuss/.*'; // 讨论区
// 监听 URL 变化
function initUrlChange() {
let isLoad = false;
const load = () => {
if (isLoad) return;
isLoad = true;
const oldPushState = history.pushState;
const oldReplaceState = history.replaceState;
history.pushState = function pushState(...args) {
const res = oldPushState.apply(this, args);
window.dispatchEvent(new Event('urlchange'));
return res;
};
history.replaceState = function replaceState(...args) {
const res = oldReplaceState.apply(this, args);
window.dispatchEvent(new Event('urlchange'));
return res;
};
window.addEventListener('popstate', () => {
window.dispatchEvent(new Event('urlchange'));
});
};
return load;
}
// 根据 URL 启动对应功能
function clearAndStart(url, timeout, isAddEvent) {
let pageLst = ['all', 'pb', 'pblist', 'search', 'study'];
let urlLst = [allUrl, pbUrl, pblistUrl, searchUrl, studyUrl];
let funcLst = [getData, getpb, getPblistData, getSearch, getStudyData];
for (let index = 0; index < urlLst.length; index++) {
if (url.match(urlLst[index])) {
let id = setInterval(funcLst[index], timeout);
GM_setValue(pageLst[index], id);
}
}
if (isAddEvent) {
window.addEventListener('urlchange', () => {
clearAndStart(location.href, 1000, false);
});
}
}
// 启动插件
clearAndStart(location.href, 1000, true);
```
--------------------------------
### Automatic Dark Mode Switching for LeetCode
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code automatically switches LeetCode's website between dark and light modes based on the time of day (8 AM to 8 PM). It uses a custom API to set the theme and updates local storage to maintain the setting. The functionality is controlled by a user preference flag 'switchdark'.
```javascript
// 切换主题 API
let lcTheme = mode => {
let headers = {
accept: '*/*',
'accept-language': 'zh-CN,zh;q=0.9',
'content-type': 'application/json'
};
let body = {
operationName: 'setTheme',
query: "
mutation setTheme($darkMode: String!) {
setDarkSide(darkMode: $darkMode)
}
",
variables: { darkMode: mode } // 'light' | 'dark'
};
ajaxReq('POST', lcnojgo, headers, body, () => {});
};
// 自动切换逻辑
if (GM_getValue('switchdark')) {
let h = new Date().getHours();
if (h >= 8 && h < 20) {
lcTheme('light');
localStorage.setItem('lc-dark-side', 'light');
console.log('修改至light mode...');
} else {
lcTheme('dark');
localStorage.setItem('lc-dark-side', 'dark');
console.log('修改至dark mode...');
}
}
```
--------------------------------
### Define Arithmetic Rating Levels in JavaScript
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
Defines the descriptive content for each arithmetic rating level, from 1 (no algorithm requirement) to 11 (competition content beyond interview scope). This is a string constant used for explaining the rating system.
```javascript
const levelContent = `
1 无算法要求
2 知道常用数据结构和算法并简单使用
3 理解常用数据结构和算法
4 掌握常用数据结构和算法
5 熟练掌握常用数据结构和算法,初步了解高级数据结构
6 深入理解并灵活应用数据结构和算法,理解高级数据结构
7 结合多方面的数据结构和算法,处理较复杂问题
8 掌握不同的数据结构与算法之间的关联性,处理复杂问题
9 处理复杂问题,对时间复杂度的要求更严格
10 非常复杂的问题,非常高深的数据结构和算法(如线段树、树状数组)
11 竞赛内容,知识点超出面试范围
`;
```
--------------------------------
### Fetch Arithmetic Rating Data with JavaScript
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
An asynchronous JavaScript function `getPromiseLevel` that fetches arithmetic rating data from a specified URL using `GM_xmlhttpRequest`. It parses the JSON response, processes it into a `levelData` object, and stores it using `GM_setValue`. It handles potential 'NaN' values by replacing them with 'null'.
```javascript
async function getPromiseLevel() {
let res = await new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'get',
url: levelUrl + '?timeStamp=' + new Date().getTime(),
onload: function(res) { resolve(res); }
});
});
if (res.status === 200) {
levelData = {};
let json = JSON.parse(res.response.replace(/\bNaN\b/g, 'null'));
for (const element of json) {
levelData[element.ID] = element;
}
GM_setValue('levelData', JSON.stringify(levelData));
}
}
```
--------------------------------
### Display Contest Rating and Info on LeetCode Problem Detail Page (JavaScript)
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript function enhances the LeetCode problem detail page by displaying custom contest ratings and related information. It retrieves the problem ID from the page title, finds the difficulty display element, and replaces it with the contest rating if available and the feature is enabled. It also constructs and appends links to the specific contest and displays the problem's index within that contest, along with an 'arithmetic rating' if available.
```javascript
function getpb() {
let switchrealoj = GM_getValue('switchrealoj');
let curUrl = location.href;
let t = document.querySelector('.text-title-large');
if (t == null) return;
let data = t.textContent.split('.');
let id = data[0].trim();
let colorA = ['.text-difficulty-hard', '.text-difficulty-easy', '.text-difficulty-medium'];
let colorSpan;
for (const color of colorA) {
colorSpan = document.querySelector(color);
if (colorSpan) break;
}
if (t2rate[id] != null && GM_getValue('switchpbscore')) {
colorSpan.innerHTML = t2rate[id]['Rating'];
}
if (t2rate[id] != null) {
let contestUrl = 'https://leetcode.cn/contest/';
let span = document.createElement('span');
span.innerText = t2rate[id]['ContestID_zh'];
let abody = document.createElement('a');
abody.setAttribute('href', contestUrl + t2rate[id]['ContestSlug']);
abody.setAttribute('target', '_blank');
abody.appendChild(span);
let span2 = document.createElement('span');
span2.innerText = t2rate[id]['ProblemIndex'];
let levelData = JSON.parse(GM_getValue('levelData', '{}').toString());
if (levelData[id] != null) {
let span3 = document.createElement('span');
span3.innerText = '算术评级: ' + levelData[id]['Level'];
}
}
}
```
--------------------------------
### LeetCode Submission Monitoring for Status Update
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code intercepts fetch requests to monitor user submissions on LeetCode. It checks if a submission's result URL matches the expected pattern and if the status is 'Accepted' or indicates failure. Upon detecting a submission, it updates a local cache ('pbstatus') with the problem's status (SOLVED or ATTEMPTED).
```javascript
// 监听 fetch 请求
function pbsubmitListen() {
var originalFetch = fetch;
window.unsafeWindow.fetch = function() {
return originalFetch.apply(this, arguments).then(function(response) {
let checkUrl = 'https://leetcode.cn/submissions/detail/[0-9]*/check/.*';
let clonedResponse = response.clone();
clonedResponse.text().then(function(bodyText) {
if (clonedResponse.url.match(checkUrl) && clonedResponse.status == 200) {
let resp = JSON.parse(bodyText);
if (resp?.status_msg?.includes('Accepted')) {
// 提交成功,更新状态为 SOLVED
let pbstatus = JSON.parse(GM_getValue('pbstatus', '{}').toString());
let slug = getSlug(location.href);
if (!pbstatus[slug]) pbstatus[slug] = {};
pbstatus[slug]['status'] = 'SOLVED';
GM_setValue('pbstatus', JSON.stringify(pbstatus));
console.log('提交成功,当前题目状态已更新');
} else if (resp?.status_msg) {
// 提交失败,更新状态为 ATTEMPTED
let pbstatus = JSON.parse(GM_getValue('pbstatus', '{}').toString());
let slug = getSlug(location.href);
if (!pbstatus[slug]) pbstatus[slug] = {};
pbstatus[slug]['status'] = 'ATTEMPTED';
GM_setValue('pbstatus', JSON.stringify(pbstatus));
console.log('提交失败, 当前题目状态已更新');
}
}
});
return response;
});
};
}
```
--------------------------------
### Render Custom Difficulty Scores on LeetCode Problem List (JavaScript)
Source: https://context7.com/zhang-wangz/leetcoderating/llms.txt
This JavaScript code modifies the LeetCode problem listing page to display custom difficulty scores instead of the default labels. It retrieves user preferences for enabling this feature and fetches contest rating data. The function iterates through the problem list, identifies the difficulty element, and replaces its text content with the corresponding contest rating or a translated difficulty if no rating is found. It also includes logic for inserting 'arithmetic rating' if enabled.
```javascript
function getData() {
let switchpbRepo = GM_getValue('switchpbRepo');
let switchTea = GM_getValue('switchTea');
let switchrealoj = GM_getValue('switchrealoj');
let switchlevel = GM_getValue('switchlevel');
let arr = document.querySelector('[class*="pb-[80px]"]');
if (arr == null) return;
t2rate = JSON.parse(GM_getValue('t2ratedb', '{}').toString());
if (switchTea) {
let first = arr.firstChild;
if (!first.textContent.includes('灵茶题集')) {
createProblemCard({
title: '灵茶题集-' + getCurrentDate(3),
pburl: 'https://docs.qq.com/sheet/DWGFoRGVZRmxNaXFz',
difficulty: '暂无',
rate: '暂无',
parentNodeList: arr
});
}
}
if (switchpbRepo) {
let childs = arr.childNodes;
for (let idx = 0; idx < childs.length; idx++) {
let v = childs[idx];
let t = v.textContent;
let data = t.split('.');
let id = data[0].trim();
let $item = $(v);
let difficulty = $item.find('.text-sd-medium, .text-sd-easy, .text-sd-hard').first();
if (t2rate[id] != null) {
let ndScore = t2rate[id]['Rating'];
difficulty.text(ndScore);
} else {
let nd2ch = {
'text-sd-easy': '简单',
'text-sd-medium': '中等',
'text-sd-hard': '困难'
};
difficulty.text(nd2ch[difficulty.attr('class')]);
}
if (switchlevel && levelData[id]) {
let levelText = '算术评级: ' + levelData[id]['Level'];
}
}
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.