-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgetRandomId.js
66 lines (65 loc) · 2.06 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { readdirSync } from 'node:fs'
import { getQuestionListJson } from '#resources/headers/questionListJson.js'
import { graphql } from '#common/utils/http/graphql.js'
import { DefaultLimit } from '#common/constants/question.const.js'
/**
* 获取指定页数的ids
*/
export async function getIds(index, limit = DefaultLimit) {
const res = await graphql(getQuestionListJson(index, limit))
return res?.data?.problemsetQuestionList?.questions?.map(
q => q.frontendQuestionId,
)
}
/**
* 获取总数
* @returns {Promise<any>}
*/
export function getCount() {
return graphql(getQuestionListJson(0)).then(
res => res?.data?.problemsetQuestionList?.total,
)
}
/**
* 获取随机的一个id 只要保证没有存在过就可以
*/
export async function getRandomId() {
// 去除所有的标题 剩下的就是id
const parse = name => name.replace(/\.[a-zA-Z0-9-]+$/i, '')
// 获取一个 递归的获取 总会有一个 直到数量到达最大值
const getOne = async (waitIndexList, localIds) => {
const randomIndex = waitIndexList[random(waitIndexList.length)]
const ids = await getIds(randomIndex)
// 过滤后的结果
const filtered = ids.filter(o => !localIds.includes(o))
if (randomIndex === undefined)
return null
if (filtered.length) {
return filtered[random(filtered.length)]
}
else {
waitIndexList.splice(waitIndexList.findIndex(i => i === randomIndex))
return await getOne(waitIndexList, localIds)
}
}
// 所有本地题目的id
const allLocalIds = readdirSync(process.cwd()).map(parse)
// 最大的数量
const maxLength = await getCount()
const waitIndexList = Array.from({
length: Math.ceil(maxLength / DefaultLimit),
}).map((_, i) => i)
const one = await getOne(waitIndexList, allLocalIds)
if (one === null)
console.log('恭喜!你已经刷完了所有的题目!')
else
return one
}
/**
* 获取长度内的随机数组下标
* @param len 默认值10
* @returns {number}
*/
export function random(len = 10) {
return Math.trunc((Math.random() * len) % len)
}