-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_problems.js
More file actions
executable file
·79 lines (66 loc) · 2.36 KB
/
fetch_problems.js
File metadata and controls
executable file
·79 lines (66 loc) · 2.36 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env node
// This is a script to fetch problems from leetcode.com automatically.
const https = require('https');
const { debuglog } = require('util');
const { readFileSync, writeFileSync } = require('fs');
const HOSTNAME = 'leetcode.com';
const PATH = '/api/problems/all/';
const COOKIE = 'LEETCODE_SESSION=ToBeAddWhenRequired';
const updateReadme = async(problemCount) => {
// fetch problems
const problemInfo = await new Promise((resolve, reject) => {
const req = https.request({
hostname: HOSTNAME,
path: PATH,
headers: {
// When cookie is added, we could get the problem accepted status.
cookie: COOKIE,
},
}, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('error', (err) => {
console.error('Fetch response error: ', err);
reject(err);
});
res.on('end', () => {
debuglog(`info fetched from ${PATH}: ${data}`);
data = JSON.parse(data);
console.log(data['stat_status_pairs'].slice(-1));
resolve(data);
});
});
req.on('error', (err) => {
console.error('Fetch request error: ', err);
reject(err);
});
req.end();
});
// format info
const problemInfoFomatted = problemInfo['stat_status_pairs'].slice(0 - problemCount).reverse().map((item, idx) => {
const { question_id, question__title, question__title_slug } = item.stat;
const difficultyMap = { 1: 'Easy', 2: 'Medium', 3: 'Hard' };
const link = `[${question__title}](https://leetcode.com/problems/${question__title_slug}/)`;
// only acceptted problomes has solutions
const solutions = item.status === 'ac' ? `[JavaScript](./JavaScript/${question_id}.${question__title_slug}.js)` : '';
const difficulty = difficultyMap[item.difficulty.level];
const row = `|${question_id}|${link}|${solutions}|${difficulty}|`;
return row;
}).join('\n');
// update README
const readmeInfo = readFileSync('./README.md').toString();
debuglog(`README Info: ${readmeInfo}`);
const res = readmeInfo.replace(/<!-- problems-start -->([\w\W]+)<!-- problems-end -->/g,
($0, $1) =>
`<!-- problems-start -->
## Problems
| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
${problemInfoFomatted}
<!-- problems-end -->`,
);
writeFileSync('./README.md', res);
};
updateReadme(200);