-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgetRandomId.js
46 lines (45 loc) · 1.55 KB
/
getRandomId.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const {readdirSync,existsSync, mkdirSync} = require("fs");
const {normalize,} = require("path")
const {getQuestionListJson} = require("../resources/questionListJson");
const {getQuestionSearchJson} = require("../resources/questionSearchJson");
/**
* todo 需要先获取全部题目列表 需要处理随机的问题
* @returns {*[]}
*/
async function getAllIds() {
const total = await getCount();
const randomSkip = total;
const res =await fetch("https://leetcode.cn/graphql/", getQuestionListJson(0)).then((res => res.json()));
return res?.data?.problemsetQuestionList?.questions?.map(q=>q.frontendQuestionId);
}
/**
* 获取总数
* @returns {Promise<any>}
*/
async function getCount(){
return fetch("https://leetcode.cn/graphql/", getQuestionListJson(0)).then((res => res.json())).then((res)=>res?.data?.problemsetQuestionList?.total);
}
/**
* 读取本地存在的所有题目 并随机题目
*/
async function getRandomId(){
const parse = (name)=>name.replace(/\.[a-zA-Z0-9-]+$/i,"");
// src 目录
const src = normalize("./src/");
// 不存在就创建
existsSync(src)||mkdirSync(src);
// 所有本地题目
const allLocalIds = readdirSync(src).map(o=>parse(o));
const allIds =await getAllIds();
const filtered = allIds.filter(o=>!allLocalIds.includes(o));
return filtered[random(filtered.length)]
}
/**
* 获取长度内的随机数组下标
* @param len 默认值10
* @returns {number}
*/
function random(len=10){
return Math.trunc(Math.random()*len%len);
}
module.exports = {getRandomId,random,getAllIds}