forked from skygragon/leetcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathcore.js
87 lines (70 loc) · 2.39 KB
/
core.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var fs = require('fs');
var path = require('path');
var util = require('util');
var _ = require('underscore');
var log = require('./log');
var h = require('./helper');
var Plugin = require('./plugin');
var session = require('./session');
var core = new Plugin(99999999, 'core', '20170722', 'Plugins manager');
core.getProblem = function(keyword, cb) {
this.getProblems(function(e, problems) {
if (e) return cb(e);
var problem;
keyword = Number(keyword) || keyword;
if (keyword === undefined) {
var user = session.getUser();
// random select one that not AC-ed yet
problems = _.filter(problems, function(x) {
if (x.state === 'ac') return false;
if (!user.paid && x.locked) return false;
return true;
});
if (problems.length > 0)
problem = problems[_.random(problems.length - 1)];
} else {
problem = _.find(problems, function(x) {
return x.id === keyword || x.name === keyword || x.slug === keyword;
});
}
if (!problem) return cb('Problem not found!');
core.next.getProblem(problem, cb);
});
};
core.starProblem = function(problem, starred, cb) {
if (problem.starred === starred) {
log.debug('problem is already ' + (starred ? 'starred' : 'unstarred'));
return cb(null, starred);
}
core.next.starProblem(problem, starred, cb);
};
core.exportProblem = function(problem, f, codeOnly) {
var output = '';
problem.code = problem.code.replace(/\r\n/g, '\n');
if (codeOnly) {
output = problem.code;
} else {
var input = {
comment: h.langToCommentStyle(h.extToLang(f))
};
// copy problem attrs thus we can render it in template
_.extend(input, problem);
input.percent = input.percent.toFixed(2);
input.testcase = util.inspect(input.testcase || '');
// NOTE: wordwrap internally uses '\n' as EOL, so here we have to
// remove all '\r' in the raw string.
var desc = input.desc.replace(/\r\n/g, '\n')
.replace(/^ /mg, '');
var wrap = require('wordwrap')(79 - input.comment.line.length);
input.desc = wrap(desc).split('\n');
var tpl = h.getFileData(path.resolve(__dirname, '../source.tpl'));
output = _.template(tpl)(input);
}
if (h.isWindows()) {
output = output.replace(/\n/g, '\r\n');
} else {
output = output.replace(/\r\n/g, '\n');
}
fs.writeFileSync(f, output);
};
module.exports = core;