-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathaddProblem.js
More file actions
114 lines (97 loc) · 3.18 KB
/
Copy pathaddProblem.js
File metadata and controls
114 lines (97 loc) · 3.18 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const https = require('https');
const fs = require('fs');
const problemNumber = process.argv[2];
if (!problemNumber || isNaN(problemNumber)) {
console.error('Usage: node addProblem.js <problem-number>');
console.error('Example: node addProblem.js 1');
process.exit(1);
}
const searchQuery = JSON.stringify({
query: `
query problemsetQuestionList($skip: Int) {
problemsetQuestionList: questionList(
categorySlug: ""
limit: 1
skip: $skip
filters: {}
) {
questions: data {
frontendQuestionId: questionFrontendId
title
titleSlug
difficulty
topicTags { name }
}
}
}
`,
variables: { skip: parseInt(problemNumber) - 1 },
});
const options = {
hostname: 'leetcode.com',
path: '/graphql',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(searchQuery),
},
};
console.log(`Fetching problem #${problemNumber} from LeetCode...`);
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
try {
const json = JSON.parse(data);
const question = json.data?.problemsetQuestionList?.questions?.[0];
if (!question) {
console.error(
`Problem #${problemNumber} not found on LeetCode`,
);
process.exit(1);
}
const code = String(question.frontendQuestionId).padStart(4, '0');
const pattern = question.topicTags?.[0]?.name || 'Uncategorized';
const entry = {
problem: question.title,
pattern: pattern,
difficulty: question.difficulty,
link: question.titleSlug,
code: code,
};
let existing = [];
try {
const raw = fs
.readFileSync('./.problemSiteData.json', 'utf8')
.trim();
existing = raw ? JSON.parse(raw) : [];
} catch {
existing = [];
}
if (existing.find((p) => p.code === code)) {
console.log(
`Problem #${problemNumber} already exists — skipping`,
);
process.exit(0);
}
existing.push(entry);
existing.sort((a, b) => a.code.localeCompare(b.code));
fs.writeFileSync(
'./.problemSiteData.json',
JSON.stringify(existing, null, 2),
);
console.log(
`Added: [${code}] ${question.title} — ${question.difficulty} — ${pattern}`,
);
} catch (err) {
console.error('Failed to parse LeetCode response:', err.message);
process.exit(1);
}
});
});
req.on('error', (err) => {
console.error('Request failed:', err.message);
process.exit(1);
});
req.write(searchQuery);
req.end();