Skip to content

Commit 3cc0b68

Browse files
committedJan 2, 2018
Use const, let.
Signed-off-by: Eric Wang <skygragon@gmail.com>
·
2.6.72.5.0
1 parent 5f10210 commit 3cc0b68

27 files changed

+257
-261
lines changed
 

‎.eslintrc.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
module.exports = {
22
"env": {
33
"browser": false,
4-
"es6": false,
4+
"es6": true,
55
"mocha": true,
66
"node": true
77
},
8-
"extends": "google",
8+
"extends": [
9+
"google",
10+
"eslint:recommended"
11+
],
912
"rules": {
1013
"block-spacing": [2, "always"],
1114
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
@@ -14,6 +17,8 @@ module.exports = {
1417
"curly": 0,
1518
"key-spacing": [2, {align: "value"}],
1619
"max-len": [1, 120],
20+
"no-console": 1,
21+
"no-empty": [2, { "allowEmptyCatch": true }],
1722
"no-eval": 1, // we use it on purpose
1823
"no-loop-func": 1,
1924
"no-multi-spaces": 0,

‎lib/cache.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,27 @@ var path = require('path');
44

55
var h = require('./helper');
66

7-
var cache = {};
7+
const cache = {};
88

99
cache.init = function() {
1010
h.mkdir(h.getCacheDir());
1111
};
1212

1313
cache.get = function(k) {
14-
var fullpath = h.getCacheFile(k);
14+
const fullpath = h.getCacheFile(k);
1515
if (!fs.existsSync(fullpath)) return null;
1616

17-
var v = JSON.parse(fs.readFileSync(fullpath));
18-
return v;
17+
return JSON.parse(fs.readFileSync(fullpath));
1918
};
2019

2120
cache.set = function(k, v) {
22-
var fullpath = h.getCacheFile(k);
21+
const fullpath = h.getCacheFile(k);
2322
fs.writeFileSync(fullpath, JSON.stringify(v));
2423
return true;
2524
};
2625

2726
cache.del = function(k) {
28-
var fullpath = h.getCacheFile(k);
27+
const fullpath = h.getCacheFile(k);
2928
if (!fs.existsSync(fullpath)) return false;
3029

3130
fs.unlinkSync(fullpath);
@@ -38,8 +37,8 @@ cache.list = function() {
3837
return path.extname(filename) === '.json';
3938
})
4039
.map(function(filename) {
41-
var k = path.basename(filename, '.json');
42-
var stat = fs.statSync(h.getCacheFile(k));
40+
const k = path.basename(filename, '.json');
41+
const stat = fs.statSync(h.getCacheFile(k));
4342
return {
4443
name: k,
4544
size: stat.size,

‎lib/chalk.js

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@ var _ = require('underscore');
33
var style = require('ansi-styles');
44
var supportsColor = require('supports-color');
55

6-
var chalk = {
6+
const chalk = {
77
enabled: supportsColor.stdout,
88
use256: supportsColor.stdout && supportsColor.stdout.has256,
99
themes: {},
1010
theme: {}
1111
};
1212

13-
var pres = [];
14-
var posts = [];
13+
const pres = [];
14+
const posts = [];
1515

16-
var DEFAULT = {
16+
const DEFAULT = {
1717
black: '#000000',
1818
blue: '#0000ff',
1919
cyan: '#00ffff',
@@ -26,12 +26,12 @@ var DEFAULT = {
2626
};
2727

2828
chalk.setTheme = function(name) {
29-
var theme = this.themes[name] || this.themes.default || {};
29+
const theme = this.themes[name] || this.themes.default || {};
3030
this.theme = _.extendOwn(DEFAULT, theme);
3131
};
3232

3333
chalk.sprint = function(s, hex) {
34-
var color = chalk.use256 ? style.color.ansi256.hex(hex) : style.color.ansi.hex(hex);
34+
const color = chalk.use256 ? style.color.ansi256.hex(hex) : style.color.ansi.hex(hex);
3535
return color + s + style.color.close;
3636
};
3737

@@ -44,9 +44,7 @@ chalk.print = function(s) {
4444
chalk.wrap = function(pre, post) {
4545
pres.push(pre);
4646
posts.unshift(post);
47-
var f = function(s) {
48-
return chalk.print(s);
49-
};
47+
const f = function(s) { return chalk.print(s); };
5048
Object.setPrototypeOf(f, chalk);
5149
return f;
5250
};
@@ -55,11 +53,11 @@ function bgName(s) { return 'bg' + s[0].toUpperCase() + s.substr(1); }
5553

5654
chalk.init = function() {
5755
require('./helper').getCodeDirData('colors').forEach(function(f) {
58-
var o = {};
56+
const o = {};
5957
_.pairs(f.data).forEach(function(x) {
60-
var k = x[0];
61-
var v = x[1];
62-
var bgK = bgName(k);
58+
const k = x[0];
59+
const v = x[1];
60+
const bgK = bgName(k);
6361

6462
if (chalk.use256) {
6563
o[k] = style.color.ansi256.hex(v);
@@ -80,7 +78,7 @@ chalk.init = function() {
8078
},
8179
configurable: true
8280
});
83-
var bgcolor = bgName(color);
81+
const bgcolor = bgName(color);
8482
Object.defineProperty(chalk, bgcolor, {
8583
get: function() {
8684
return chalk.wrap(chalk.theme[bgcolor], style.bgColor.close);

‎lib/cli.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,24 +27,22 @@ function initIcon() {
2727
function initLogLevel() {
2828
log.init();
2929

30-
var level = 'INFO';
30+
let level = 'INFO';
3131
if (process.argv.indexOf('-v') >= 0) level = 'DEBUG';
3232
if (process.argv.indexOf('-vv') >= 0) level = 'TRACE';
3333

3434
// print HTTP details in TRACE
3535
if (level === 'TRACE') {
36-
var request = require('request');
36+
const request = require('request');
3737
request.debug = true;
3838

3939
console.error = _.wrap(console.error, function(func) {
40-
var args = _.toArray(arguments);
40+
let args = _.toArray(arguments);
4141
args.shift();
4242

4343
// FIXME: hack HTTP request log, hope no one else use it...
4444
if (args.length > 0 && args[0].indexOf('REQUEST ') === 0) {
45-
args = args.map(function(arg) {
46-
return h.printSafeHTTP(arg);
47-
});
45+
args = args.map(function(arg) { return h.printSafeHTTP(arg); });
4846
log.trace.apply(log, args);
4947
} else {
5048
log.info.apply(log, args);

‎lib/commands/cache.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ var log = require('../log');
77
var cache = require('../cache');
88
var session = require('../session');
99

10-
var cmd = {
10+
const cmd = {
1111
command: 'cache [keyword]',
1212
desc: 'Manage local cache',
1313
builder: function(yargs) {
@@ -33,7 +33,7 @@ var cmd = {
3333
cmd.handler = function(argv) {
3434
session.argv = argv;
3535

36-
var caches = cache.list()
36+
const caches = cache.list()
3737
.filter(function(f) {
3838
return argv.keyword.length === 0 || f.name.startsWith(argv.keyword + '.');
3939
});
@@ -42,7 +42,7 @@ cmd.handler = function(argv) {
4242
caches.forEach(function(f) { cache.del(f.name); });
4343
} else {
4444
_.sortBy(caches, function(f) {
45-
var x = parseInt(f.name.split('.')[0], 10);
45+
let x = parseInt(f.name.split('.')[0], 10);
4646
if (Number.isNaN(x)) x = 0;
4747
return x;
4848
})

‎lib/commands/config.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var config = require('../config');
88
var log = require('../log');
99
var session = require('../session');
1010

11-
var cmd = {
11+
const cmd = {
1212
command: 'config [key] [value]',
1313
aliases: ['conf', 'cfg', 'setting'],
1414
desc: 'Manage user configs',
@@ -49,7 +49,7 @@ function prettyConfig(cfg) {
4949
}
5050

5151
function loadConfig(showall) {
52-
var cfg = showall ? config.getAll(true) : nconf.get();
52+
const cfg = showall ? config.getAll(true) : nconf.get();
5353
return _.omit(cfg, 'type');
5454
}
5555

@@ -65,7 +65,7 @@ cmd.handler = function(argv) {
6565
if (argv.key.length === 0)
6666
return log.info(prettyConfig(loadConfig(argv.all)));
6767

68-
var v = nconf.get(argv.key);
68+
const v = nconf.get(argv.key);
6969

7070
// delete
7171
if (argv.delete) {

‎lib/commands/list.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ var log = require('../log');
99
var core = require('../core');
1010
var session = require('../session');
1111

12-
var cmd = {
12+
const cmd = {
1313
command: 'list [keyword]',
1414
aliases: ['ls'],
1515
desc: 'List questions',
@@ -47,7 +47,7 @@ cmd.handler = function(argv) {
4747
core.filterProblems(argv, function(e, problems) {
4848
if (e) return log.fail(e);
4949

50-
var word = argv.keyword.toLowerCase();
50+
const word = argv.keyword.toLowerCase();
5151
if (word) {
5252
if (word.endsWith(word.substr(-1).repeat(6))) {
5353
log.warn('Hmmm...you might need a new keyboard?');
@@ -57,8 +57,8 @@ cmd.handler = function(argv) {
5757
});
5858
}
5959

60-
var stat = {};
61-
var KEYS = ['locked', 'starred', 'ac', 'notac', 'None', 'Easy', 'Medium', 'Hard'];
60+
const stat = {};
61+
const KEYS = ['locked', 'starred', 'ac', 'notac', 'None', 'Easy', 'Medium', 'Hard'];
6262
KEYS.forEach(function(x) { stat[x] = 0; });
6363

6464
problems = _.sortBy(problems, function(x) { return -x.id; });
@@ -78,12 +78,12 @@ cmd.handler = function(argv) {
7878
problem.percent);
7979

8080
if (argv.extra) {
81-
var badges = [problem.category];
81+
let badges = [problem.category];
8282
badges = badges.concat(problem.companies || []);
8383
badges = badges.concat(problem.tags || []);
8484

85-
var buf = [];
86-
var len = 0;
85+
let buf = [];
86+
let len = 0;
8787
badges.forEach(function(x) {
8888
if (len + x.length + 3 >= 60) {
8989
log.printf('%12s%s', ' ', chalk.dim(buf.join(' | ')));

‎lib/commands/plugin.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var log = require('../log');
88
var Plugin = require('../plugin');
99
var session = require('../session');
1010

11-
var cmd = {
11+
const cmd = {
1212
command: 'plugin [name]',
1313
aliases: ['extension', 'ext'],
1414
desc: 'Manage plugins',
@@ -62,7 +62,7 @@ var cmd = {
6262
cmd.handler = function(argv) {
6363
session.argv = argv;
6464

65-
var name = argv.name;
65+
const name = argv.name;
6666
if (argv.install) {
6767
Plugin.install(name, function(e, plugin) {
6868
if (e) return log.error(e);
@@ -71,28 +71,27 @@ cmd.handler = function(argv) {
7171
return;
7272
}
7373

74-
var plugins = Plugin.plugins;
74+
let plugins = Plugin.plugins;
7575
if (name) {
7676
plugins = plugins.filter(function(p) {
7777
return p.name === name;
7878
});
7979
}
8080
if (plugins.length === 0) return log.error('Plugin not found!');
8181

82-
var plugin = plugins[0];
83-
var fullpath = h.getPluginFile(plugin.file);
84-
var newname;
82+
const plugin = plugins[0];
83+
const fullpath = h.getPluginFile(plugin.file);
8584

8685
if (argv.enable) {
8786
if (plugin.enabled) return;
88-
newname = h.getPluginFile(plugin.file.substr(1));
87+
const newname = h.getPluginFile(plugin.file.substr(1));
8988

9089
fs.rename(fullpath, newname, function(e) {
9190
if (e) log.error(e.message);
9291
});
9392
} else if (argv.disable) {
9493
if (!plugin.enabled) return;
95-
newname = h.getPluginFile('.' + plugin.file);
94+
const newname = h.getPluginFile('.' + plugin.file);
9695

9796
fs.rename(fullpath, newname, function(e) {
9897
if (e) log.error(e.message);

‎lib/commands/show.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ var config = require('../config');
1313
var core = require('../core');
1414
var session = require('../session');
1515

16-
var cmd = {
16+
const cmd = {
1717
command: 'show [keyword]',
1818
aliases: ['view', 'pull'],
1919
desc: 'Show question',
@@ -68,28 +68,28 @@ var cmd = {
6868

6969
function genFileName(problem, lang) {
7070
// try to use a new filename to avoid overwrite by mistake
71-
var name = problem.id + '.' + problem.slug + h.langToExt(lang);
72-
var i = 0;
71+
let name = problem.id + '.' + problem.slug + h.langToExt(lang);
72+
let i = 0;
7373
while (fs.existsSync(name))
7474
name = problem.id + '.' + problem.slug + '.' + (i++) + h.langToExt(lang);
7575
return name;
7676
}
7777

7878
function showProblem(problem, argv) {
79-
var taglist = [problem.category]
79+
const taglist = [problem.category]
8080
.concat(problem.companies || [])
8181
.concat(problem.tags || [])
8282
.map(function(x) { return h.badge(x, 'blue'); })
8383
.join(' ');
84-
var langlist = problem.templates
84+
const langlist = problem.templates
8585
.map(function(x) { return h.badge(x.value, 'yellow'); })
8686
.sort()
8787
.join(' ');
8888

89-
var code;
90-
var needcode = argv.gen || argv.codeonly;
89+
let code;
90+
const needcode = argv.gen || argv.codeonly;
9191
if (needcode) {
92-
var template = problem.templates.find(function(x) {
92+
const template = problem.templates.find(function(x) {
9393
return x.value === argv.lang;
9494
});
9595
if (!template) {
@@ -98,15 +98,15 @@ function showProblem(problem, argv) {
9898
return;
9999
}
100100

101-
var opts = {
101+
const opts = {
102102
lang: argv.lang,
103103
code: template.defaultCode,
104104
tpl: argv.extra ? 'detailed' : 'codeonly'
105105
};
106106
code = core.exportProblem(problem, opts);
107107
}
108108

109-
var filename;
109+
let filename;
110110
if (argv.gen) {
111111
filename = genFileName(problem, argv.lang);
112112
fs.writeFileSync(filename, code);
@@ -166,15 +166,15 @@ cmd.handler = function(argv) {
166166
if (e) return log.fail(e);
167167

168168
// random select one that not AC-ed yet
169-
var user = session.getUser();
169+
const user = session.getUser();
170170
problems = problems.filter(function(x) {
171171
if (x.state === 'ac') return false;
172172
if (!user.paid && x.locked) return false;
173173
return true;
174174
});
175-
if (problems.length === 0) return cb('Problem not found!');
175+
if (problems.length === 0) return log.fail('Problem not found!');
176176

177-
var problem = _.sample(problems);
177+
const problem = _.sample(problems);
178178
core.getProblem(problem, function(e, problem) {
179179
if (e) return log.fail(e);
180180
showProblem(problem, argv);

‎lib/commands/star.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ var log = require('../log');
55
var core = require('../core');
66
var session = require('../session');
77

8-
var cmd = {
8+
const cmd = {
99
command: 'star <keyword>',
1010
aliases: ['like', 'favorite'],
1111
desc: 'Star favorite question',

‎lib/commands/stat.js

Lines changed: 38 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ var core = require('../core');
99
var session = require('../session');
1010
var h = require('../helper');
1111

12-
var cmd = {
12+
const cmd = {
1313
command: 'stat',
1414
desc: 'Show statistics',
1515
aliases: ['stats', 'progress', 'report'],
@@ -51,25 +51,25 @@ function bar(c, n) {
5151
}
5252

5353
function printLine(key, done, all) {
54-
var n = 30;
55-
var percent = (all > 0) ? done / all : 0;
56-
var x = Math.ceil(n * percent);
54+
const n = 30;
55+
const percent = (all > 0) ? done / all : 0;
56+
const x = Math.ceil(n * percent);
5757
log.printf(' %s\t%3d/%-3d (%.2f%%) %s%s',
5858
h.prettyLevel(key), done, all, 100 * percent,
5959
chalk.green(bar('█', x)),
6060
chalk.red(bar('░', n - x)));
6161
}
6262

6363
function showProgress(problems) {
64-
var stats = {
64+
const stats = {
6565
easy: {all: 0, ac: 0},
6666
medium: {all: 0, ac: 0},
6767
hard: {all: 0, ac: 0}
6868
};
6969

7070
problems.forEach(function(problem) {
71-
var level = problem.level.toLowerCase();
72-
var state = problem.state.toLowerCase();
71+
const level = problem.level.toLowerCase();
72+
const state = problem.state.toLowerCase();
7373

7474
if (!(level in stats)) return;
7575
++stats[level].all;
@@ -83,14 +83,14 @@ function showProgress(problems) {
8383
printLine('Hard', stats.hard.ac, stats.hard.all);
8484
}
8585

86-
var CHARS = {
86+
const CHARS = {
8787
ac: h.isWindows() ? 'O ' : '▣ ',
8888
notac: h.isWindows() ? 'X ' : '▤ ',
8989
none: h.isWindows() ? 'o ' : '⬚ ',
9090
};
9191

9292
function showGraph(problems) {
93-
var ICONS = {
93+
const ICONS = {
9494
ac: chalk.green(CHARS.ac),
9595
notac: chalk.red(CHARS.notac),
9696
none: chalk.gray(CHARS.none),
@@ -100,22 +100,22 @@ function showGraph(problems) {
100100
// row header is 4 bytes
101101
// each question takes 2 bytes
102102
// each group has 10 questions, which takes (2*10=20) + 3 paddings
103-
var groups = Math.floor((h.width - 4) / (3 + 2 * 10));
103+
let groups = Math.floor((h.width - 4) / (3 + 2 * 10));
104104
if (groups < 1) groups = 1;
105105
if (groups > 5) groups = 5;
106106

107-
var header = _.range(groups)
107+
const header = _.range(groups)
108108
.map(function(x) { return sprintf('%5d%18d', x * 10 + 1, x * 10 + 10); })
109109
.join('');
110110
log.info(' ' + header);
111111

112-
var graph = [];
112+
const graph = [];
113113
problems.forEach(function(problem) {
114114
graph[problem.id] = ICONS[problem.state] || ICONS.none;
115115
});
116116

117-
var line = [sprintf(' %03d', 0)];
118-
for (var i = 1, n = graph.length; i <= n; ++i) {
117+
let line = [sprintf(' %03d', 0)];
118+
for (let i = 1, n = graph.length; i <= n; ++i) {
119119
// padding before group
120120
if (i % 10 === 1) line.push(' ');
121121

@@ -136,64 +136,63 @@ function showGraph(problems) {
136136
}
137137

138138
function showCal() {
139-
var MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
140-
var WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
141-
var ICONS = [
139+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
140+
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
141+
const ICONS = [
142142
CHARS.none,
143143
chalk.sprint(CHARS.ac, '#ffffcc'),
144144
chalk.sprint(CHARS.ac, '#ccff66'),
145145
chalk.sprint(CHARS.ac, '#66cc33'),
146146
chalk.sprint(CHARS.ac, '#00ff00')
147147
];
148148

149-
var N_MONTHS = 12;
150-
var N_WEEKS = 53;
151-
var N_WEEKDAYS = 7;
149+
const N_MONTHS = 12;
150+
const N_WEEKS = 53;
151+
const N_WEEKDAYS = 7;
152152

153-
var now = moment();
153+
const now = moment();
154154

155155
// load historical stats
156-
var graph = [];
157-
var stats = require('../cache').get(h.KEYS.stat) || {};
156+
const graph = [];
157+
const stats = require('../cache').get(h.KEYS.stat) || {};
158158
_.keys(stats).forEach(function(k) {
159-
var v = stats[k].ac || 0;
159+
const v = stats[k].ac || 0;
160160
if (v === 0) return;
161161

162-
var d = moment(k, 'YYYY-MM-DD');
162+
const d = moment(k, 'YYYY-MM-DD');
163163
graph[now.diff(d, 'days')] = v;
164164
});
165165

166166
// print header
167-
var buf = Buffer.alloc(120, ' ', 'ascii');
168-
for (var i = 0; i <= N_MONTHS; ++i) {
167+
const buf = Buffer.alloc(120, ' ', 'ascii');
168+
for (let i = 0; i <= N_MONTHS; ++i) {
169169
// for day 1 in each month, calculate its column position in graph
170-
var d = now.clone().subtract(i, 'months').date(1);
171-
var idx = now.diff(d, 'days');
170+
const d = now.clone().subtract(i, 'months').date(1);
171+
const idx = now.diff(d, 'days');
172172

173-
var j = (N_WEEKS - idx / N_WEEKDAYS + 1) * 2;
173+
const j = (N_WEEKS - idx / N_WEEKDAYS + 1) * 2;
174174
if (j >= 0) buf.write(MONTHS[d.month()], j);
175175
}
176176
log.printf('%7s%s', ' ', buf.toString());
177177

178178
// print graph
179-
var idx;
180-
for (var i = 0; i < N_WEEKDAYS; ++i) {
181-
var line = [];
179+
for (let i = 0; i < N_WEEKDAYS; ++i) {
180+
const line = [];
182181
// print day in week
183-
idx = (now.day() + i + 1) % N_WEEKDAYS;
182+
const idx = (now.day() + i + 1) % N_WEEKDAYS;
184183
line.push(sprintf('%4s ', WEEKDAYS[idx]));
185184

186-
for (var j = 0; j < N_WEEKS; ++j) {
187-
idx = (N_WEEKS - j - 1) * N_WEEKDAYS + N_WEEKDAYS - i - 1;
188-
var d = now.clone().subtract(idx, 'days');
185+
for (let j = 0; j < N_WEEKS; ++j) {
186+
let idx = (N_WEEKS - j - 1) * N_WEEKDAYS + N_WEEKDAYS - i - 1;
187+
const d = now.clone().subtract(idx, 'days');
189188

190189
// map count to icons index:
191190
// [0] => 0, [1,5] => 1, [6,10] => 2, [11,15] => 3, [16,) => 4
192-
var count = graph[idx] || 0;
191+
const count = graph[idx] || 0;
193192
idx = Math.floor((count - 1) / 5) + 1;
194193
if (idx > 4) idx = 4;
195194

196-
var icon = ICONS[idx];
195+
let icon = ICONS[idx];
197196
// use different colors for adjacent months
198197
if (idx === 0 && d.month() % 2) icon = chalk.gray(icon);
199198
line.push(icon);

‎lib/commands/submission.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ var Queue = require('../queue');
1010
var core = require('../core');
1111
var session = require('../session');
1212

13-
var cmd = {
13+
const cmd = {
1414
command: 'submission [keyword]',
1515
desc: 'Download submission code',
1616
builder: function(yargs) {
@@ -50,7 +50,7 @@ var cmd = {
5050
};
5151

5252
function doTask(problem, queue, cb) {
53-
var argv = queue.ctx.argv;
53+
const argv = queue.ctx.argv;
5454

5555
function onTaskDone(e, msg) {
5656
// NOTE: msg color means different purpose:
@@ -66,7 +66,7 @@ function doTask(problem, queue, cb) {
6666
if (argv.extra) {
6767
// have to get problem details, e.g. problem description.
6868
core.getProblem(problem.id, function(e, problem) {
69-
if (e) return done(e);
69+
if (e) return cb(e);
7070
exportSubmission(problem, argv, onTaskDone);
7171
});
7272
} else {
@@ -88,12 +88,12 @@ function exportSubmission(problem, argv, cb) {
8888
return cb('No submissions in required language.');
8989

9090
// if no accepted, use the latest non-accepted one
91-
var submission = submissions.find(function(x) {
91+
const submission = submissions.find(function(x) {
9292
return x.status_display === 'Accepted';
9393
}) || submissions[0];
9494
submission.ac = (submission.status_display === 'Accepted');
9595

96-
var f = sprintf('%s/%d.%s.%s.%s%s',
96+
const f = sprintf('%s/%d.%s.%s.%s%s',
9797
argv.outdir,
9898
problem.id,
9999
problem.slug,
@@ -109,7 +109,7 @@ function exportSubmission(problem, argv, cb) {
109109
core.getSubmission(submission, function(e, submission) {
110110
if (e) return cb(e);
111111

112-
var opts = {
112+
const opts = {
113113
lang: submission.lang,
114114
code: submission.code,
115115
tpl: argv.extra ? 'detailed' : 'codeonly'
@@ -123,7 +123,7 @@ function exportSubmission(problem, argv, cb) {
123123

124124
cmd.handler = function(argv) {
125125
session.argv = argv;
126-
var q = new Queue(null, {argv: argv}, doTask);
126+
const q = new Queue(null, {argv: argv}, doTask);
127127

128128
if (argv.all) {
129129
core.getProblems(function(e, problems) {

‎lib/commands/submit.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ var log = require('../log');
1010
var core = require('../core');
1111
var session = require('../session');
1212

13-
var cmd = {
13+
const cmd = {
1414
command: 'submit <filename>',
1515
aliases: ['push', 'commit'],
1616
desc: 'Submit code',
@@ -28,18 +28,18 @@ var cmd = {
2828
function printResult(actual, k) {
2929
if (!actual.hasOwnProperty(k)) return;
3030

31-
var v = actual[k] || '';
32-
var lines = Array.isArray(v) ? v : [v];
31+
const v = actual[k] || '';
32+
const lines = Array.isArray(v) ? v : [v];
3333
lines.forEach(function(line) {
3434
if (k !== 'state') line = k + ': ' + line;
3535
log.info(' ' + h.prettyText(' ' + line, actual.ok));
3636
});
3737
}
3838

3939
function printLine() {
40-
var args = _.toArray(arguments);
41-
var actual = args.shift();
42-
var line = util.format.apply(util, args);
40+
const args = _.toArray(arguments);
41+
const actual = args.shift();
42+
const line = util.format.apply(util, args);
4343
log.info(' ' + h.prettyText(' ' + line, actual.ok));
4444
}
4545

@@ -50,7 +50,7 @@ cmd.handler = function(argv) {
5050

5151
// use the 1st section in filename as keyword
5252
// e.g. two-sum.cpp, or two-sum.78502271.ac.cpp
53-
var keyword = h.getFilename(argv.filename).split('.')[0];
53+
const keyword = h.getFilename(argv.filename).split('.')[0];
5454

5555
core.getProblem(keyword, function(e, problem) {
5656
if (e) return log.fail(e);
@@ -60,7 +60,7 @@ cmd.handler = function(argv) {
6060
core.submitProblem(problem, function(e, results) {
6161
if (e) return log.fail(e);
6262

63-
var result = results[0];
63+
const result = results[0];
6464

6565
printResult(result, 'state');
6666
printLine(result, '%d/%d cases passed (%s)',
@@ -72,11 +72,11 @@ cmd.handler = function(argv) {
7272
if (e || !submission || !submission.distributionChart)
7373
return log.warn('Failed to get submission beat ratio.');
7474

75-
var lang = submission.distributionChart.lang;
76-
var scores = submission.distributionChart.distribution;
77-
var myRuntime = parseFloat(result.runtime);
75+
const lang = submission.distributionChart.lang;
76+
const scores = submission.distributionChart.distribution;
77+
const myRuntime = parseFloat(result.runtime);
7878

79-
var ratio = 0.0;
79+
let ratio = 0.0;
8080
scores.forEach(function(score) {
8181
if (parseFloat(score[0]) > myRuntime)
8282
ratio += parseFloat(score[1]);

‎lib/commands/test.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var log = require('../log');
88
var core = require('../core');
99
var session = require('../session');
1010

11-
var cmd = {
11+
const cmd = {
1212
command: 'test <filename>',
1313
aliases: ['run'],
1414
desc: 'Test code',
@@ -39,13 +39,13 @@ var cmd = {
3939
function printResult(actual, expect, k) {
4040
if (!actual.hasOwnProperty(k)) return;
4141
// HACk: leetcode still return 'Accepted' even the answer is wrong!!
42-
var v = actual[k] || '';
42+
const v = actual[k] || '';
4343
if (k === 'state' && v === 'Accepted') return;
4444

45-
var ok = actual.ok;
45+
let ok = actual.ok;
4646
if (expect && !_.isEqual(actual[k], expect[k])) ok = false;
4747

48-
var lines = Array.isArray(v) ? v : [v];
48+
const lines = Array.isArray(v) ? v : [v];
4949
lines.forEach(function(line) {
5050
if (k !== 'state') line = k + ': ' + line;
5151
log.info(' ' + h.prettyText(' ' + line, ok));
@@ -58,7 +58,7 @@ function runTest(argv) {
5858

5959
// use the 1st section in filename as keyword
6060
// e.g. two-sum.cpp, or two-sum.78502271.ac.cpp
61-
var keyword = h.getFilename(argv.filename).split('.')[0];
61+
const keyword = h.getFilename(argv.filename).split('.')[0];
6262

6363
core.getProblem(keyword, function(e, problem) {
6464
if (e) return log.fail(e);
@@ -80,7 +80,7 @@ function runTest(argv) {
8080
core.testProblem(problem, function(e, results) {
8181
if (e) return log.fail(e);
8282

83-
for (var i = 0; i < results.length; ++i) {
83+
for (let i = 0; i < results.length; ++i) {
8484
log.info();
8585
log.info(chalk.yellow(results[i].type));
8686

‎lib/commands/user.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ var log = require('../log');
66
var core = require('../core');
77
var session = require('../session');
88

9-
var cmd = {
9+
const cmd = {
1010
command: 'user',
1111
desc: 'Manage account',
1212
builder: function(yargs) {
@@ -30,7 +30,7 @@ var cmd = {
3030

3131
cmd.handler = function(argv) {
3232
session.argv = argv;
33-
var user = null;
33+
let user = null;
3434
if (argv.login) {
3535
// login
3636
prompt.colors = false;

‎lib/commands/version.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ var log = require('../log');
77
var Plugin = require('../plugin');
88
var session = require('../session');
99

10-
var cmd = {
10+
const cmd = {
1111
command: 'version',
1212
aliases: ['info', 'env'],
1313
desc: 'Show version info',
@@ -23,10 +23,10 @@ function printLine(k, v) {
2323
}
2424

2525
function getVersion() {
26-
var version = require('../../package.json').version;
26+
let version = require('../../package.json').version;
2727

2828
try {
29-
var commit = require('../../.env.json').commit.short;
29+
const commit = require('../../.env.json').commit.short;
3030
if (commit) version += '-' + commit;
3131
} catch (e) {}
3232

@@ -35,12 +35,12 @@ function getVersion() {
3535

3636
cmd.handler = function(argv) {
3737
session.argv = argv;
38-
var version = getVersion();
38+
const version = getVersion();
3939

4040
if (!log.isEnabled('DEBUG'))
4141
return log.info(version);
4242

43-
var logo = [
43+
const logo = [
4444
' _ _ _ ',
4545
'| | | | | | ',
4646
'| | ___ ___| |_ ___ ___ __| | ___ ',
@@ -50,9 +50,9 @@ cmd.handler = function(argv) {
5050
].join('\n');
5151
log.info(logo);
5252

53-
var h = require('../helper');
54-
var os = require('os');
55-
var config = require('../config');
53+
const h = require('../helper');
54+
const os = require('os');
55+
const config = require('../config');
5656

5757
log.info('\n[Environment]');
5858
printLine('Node', process.version);

‎lib/config.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ var nconf = require('nconf');
44

55
var h = require('./helper');
66

7-
var DEFAULT_CONFIG = {
7+
const DEFAULT_CONFIG = {
88
// usually you don't wanna change those
99
sys: {
1010
categories: [
@@ -73,12 +73,12 @@ Config.prototype.init = function() {
7373
.add('global', {type: 'literal', store: DEFAULT_CONFIG})
7474
.defaults({});
7575

76-
var cfg = nconf.get();
76+
const cfg = nconf.get();
7777
nconf.remove('local');
7878
nconf.remove('global');
7979

8080
// HACK: remove old style configs
81-
for (var x in cfg) {
81+
for (let x in cfg) {
8282
if (x === x.toUpperCase()) delete cfg[x];
8383
}
8484
delete DEFAULT_CONFIG.type;
@@ -88,7 +88,7 @@ Config.prototype.init = function() {
8888
};
8989

9090
Config.prototype.getAll = function(useronly) {
91-
var cfg = _.extendOwn({}, this);
91+
const cfg = _.extendOwn({}, this);
9292
if (useronly) delete cfg.sys;
9393
return cfg;
9494
};

‎lib/core.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var log = require('./log');
88
var h = require('./helper');
99
var Plugin = require('./plugin');
1010

11-
var core = new Plugin(99999999, 'core', '20170722', 'Plugins manager');
11+
const core = new Plugin(99999999, 'core', '20170722', 'Plugins manager');
1212

1313
core.filters = {
1414
query: {
@@ -44,7 +44,7 @@ function isACed(x) { return x.state === 'ac'; }
4444
function isLocked(x) { return x.locked; }
4545
function isStarred(x) { return x.starred; }
4646

47-
var QUERY_HANDLERS = {
47+
const QUERY_HANDLERS = {
4848
e: isLevel,
4949
E: _.negate(isLevel),
5050
m: isLevel,
@@ -64,7 +64,7 @@ core.filterProblems = function(opts, cb) {
6464
if (e) return cb(e);
6565

6666
(opts.query || '').split('').forEach(function(q) {
67-
var f = QUERY_HANDLERS[q];
67+
const f = QUERY_HANDLERS[q];
6868
if (!f) return;
6969
problems = problems.filter(function(x) { return f(x, q); });
7070
});
@@ -89,7 +89,7 @@ core.getProblem = function(keyword, cb) {
8989
if (e) return cb(e);
9090

9191
keyword = Number(keyword) || keyword;
92-
var problem = problems.find(function(x) {
92+
const problem = problems.find(function(x) {
9393
return x.id === keyword || x.name === keyword || x.slug === keyword;
9494
});
9595
if (!problem) return cb('Problem not found!');
@@ -108,7 +108,7 @@ core.starProblem = function(problem, starred, cb) {
108108

109109
core.exportProblem = function(problem, opts) {
110110
// copy problem attrs thus we can render it in template
111-
var input = _.extend({}, problem);
111+
const input = _.extend({}, problem);
112112

113113
input.code = opts.code.replace(/\r\n/g, '\n');
114114
input.comment = h.langToCommentStyle(opts.lang);
@@ -118,13 +118,13 @@ core.exportProblem = function(problem, opts) {
118118
if (opts.tpl === 'detailed') {
119119
// NOTE: wordwrap internally uses '\n' as EOL, so here we have to
120120
// remove all '\r' in the raw string.
121-
var desc = input.desc.replace(/\r\n/g, '\n').replace(/^ /mg, '⁠');
122-
var wrap = require('wordwrap')(79 - input.comment.line.length);
121+
const desc = input.desc.replace(/\r\n/g, '\n').replace(/^ /mg, '⁠');
122+
const wrap = require('wordwrap')(79 - input.comment.line.length);
123123
input.desc = wrap(desc).split('\n');
124124
}
125125

126-
var tplfile = path.join(h.getCodeDir('templates'), opts.tpl + '.tpl');
127-
var output = _.template(h.getFileData(tplfile))(input);
126+
const tplfile = path.join(h.getCodeDir('templates'), opts.tpl + '.tpl');
127+
let output = _.template(h.getFileData(tplfile))(input);
128128

129129
if (h.isWindows()) {
130130
output = output.replace(/\n/g, '\r\n');

‎lib/helper.js

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ var _ = require('underscore');
66
var mkdirp = require('mkdirp');
77
var ora = require('ora');
88

9-
var UNITS_SIZE = [
9+
const UNITS_SIZE = [
1010
{unit: 'B', name: 'Bytes', count: 1024},
1111
{unit: 'K', name: 'KBytes', count: 1024},
1212
{unit: 'M', name: 'MBytes', count: 1024},
1313
{unit: 'G', name: 'GBytes', count: -1}
1414
];
1515

16-
var UNITS_TIME = [
16+
const UNITS_TIME = [
1717
{unit: 's', name: 'seconds', count: 60},
1818
{unit: 'm', name: 'minutes', count: 60},
1919
{unit: 'h', name: 'hours', count: 24},
@@ -24,14 +24,14 @@ var UNITS_TIME = [
2424
];
2525

2626
function getUnit(units, v) {
27-
for (var i = 0; i < units.length; ++i) {
27+
for (let i = 0; i < units.length; ++i) {
2828
if (units[i].count <= 0 || v < units[i].count)
2929
return [v, units[i]];
3030
v /= units[i].count;
3131
}
3232
}
3333

34-
var LANGS = [
34+
const LANGS = [
3535
{lang: 'bash', ext: '.sh', style: '#'},
3636
{lang: 'c', ext: '.c', style: 'c'},
3737
{lang: 'cpp', ext: '.cpp', style: 'c'},
@@ -48,7 +48,7 @@ var LANGS = [
4848
{lang: 'swift', ext: '.swift', style: 'c'}
4949
];
5050

51-
var h = {};
51+
const h = {};
5252

5353
h.KEYS = {
5454
user: '../user',
@@ -70,8 +70,8 @@ h.prettyState = function(state) {
7070
};
7171

7272
h.prettyText = function(text, yesNo) {
73-
var chalk = require('./chalk');
74-
var icon = require('./icon');
73+
const chalk = require('./chalk');
74+
const icon = require('./icon');
7575
switch (yesNo) {
7676
case true: return chalk.green(icon.yes + text);
7777
case false: return chalk.red(icon.no + text);
@@ -80,17 +80,17 @@ h.prettyText = function(text, yesNo) {
8080
};
8181

8282
h.prettySize = function(n) {
83-
var res = getUnit(UNITS_SIZE, n);
83+
const res = getUnit(UNITS_SIZE, n);
8484
return res[0].toFixed(2) + res[1].unit;
8585
};
8686

8787
h.prettyTime = function(n) {
88-
var res = getUnit(UNITS_TIME, n);
88+
const res = getUnit(UNITS_TIME, n);
8989
return res[0].toFixed(0) + ' ' + res[1].name;
9090
};
9191

9292
h.prettyLevel = function(level) {
93-
var chalk = require('./chalk');
93+
const chalk = require('./chalk');
9494
switch (level.toLowerCase().trim()) {
9595
case 'easy': return chalk.green(level);
9696
case 'medium': return chalk.yellow(level);
@@ -124,23 +124,23 @@ h.statusToName = function(sc) {
124124
};
125125

126126
h.langToExt = function(lang) {
127-
var res = LANGS.find(function(x) { return x.lang === lang; });
127+
const res = LANGS.find(function(x) { return x.lang === lang; });
128128
return res ? res.ext : '.raw';
129129
};
130130

131131
h.extToLang = function(fullpath) {
132132
// HACK: compatible with old ext
133133
if (fullpath.endsWith('.py3')) return 'python3';
134134

135-
var res = _.chain(LANGS)
135+
const res = _.chain(LANGS)
136136
.filter(function(x) { return fullpath.endsWith(x.ext); })
137137
.sortBy(function(x) { return -x.ext.length; })
138138
.value();
139139
return res.length ? res[0].lang : 'unknown';
140140
};
141141

142142
h.langToCommentStyle = function(lang) {
143-
var res = LANGS.find(function(x) { return x.lang === lang; });
143+
const res = LANGS.find(function(x) { return x.lang === lang; });
144144

145145
return (res && res.style === '#') ?
146146
{start: '#', line: '#', end: '#'} :
@@ -155,11 +155,11 @@ h.mkdir = function(fullpath) {
155155
h.getCodeDirData = function(dir) {
156156
dir = h.getCodeDir(dir);
157157
return fs.readdirSync(dir).map(function(file) {
158-
var fullpath = path.join(dir, file);
159-
var ext = path.extname(file);
158+
const fullpath = path.join(dir, file);
159+
const ext = path.extname(file);
160160

161-
var name = path.basename(file, ext);
162-
var data = null;
161+
const name = path.basename(file, ext);
162+
let data = null;
163163

164164
switch (ext) {
165165
case '.js': data = require(fullpath); break;
@@ -206,14 +206,14 @@ h.getPluginFile = function(name) {
206206
};
207207

208208
h.readStdin = function(cb) {
209-
var stdin = process.stdin;
210-
var bufs = [];
209+
const stdin = process.stdin;
210+
const bufs = [];
211211

212212
console.log('NOTE: to finish the input, press ' +
213213
(this.isWindows() ? '<Ctrl-D> and <Return>' : '<Ctrl-D>'));
214214

215215
stdin.on('readable', function() {
216-
var data = stdin.read();
216+
const data = stdin.read();
217217
if (data) {
218218
// windows doesn't treat ctrl-D as EOF
219219
if (h.isWindows() && data.toString() === '\x04\r\n') {
@@ -230,13 +230,13 @@ h.readStdin = function(cb) {
230230
};
231231

232232
h.getSetCookieValue = function(resp, key) {
233-
var cookies = resp.headers['set-cookie'];
233+
const cookies = resp.headers['set-cookie'];
234234
if (!cookies) return null;
235235

236-
for (var i = 0; i < cookies.length; ++i) {
237-
var sections = cookies[i].split(';');
238-
for (var j = 0; j < sections.length; ++j) {
239-
var kv = sections[j].trim().split('=');
236+
for (let i = 0; i < cookies.length; ++i) {
237+
const sections = cookies[i].split(';');
238+
for (let j = 0; j < sections.length; ++j) {
239+
const kv = sections[j].trim().split('=');
240240
if (kv[0] === key) return kv[1];
241241
}
242242
}
@@ -253,7 +253,7 @@ h.spin = function(s) {
253253
return ora(require('./chalk').gray(s)).start();
254254
};
255255

256-
var COLORS = {
256+
const COLORS = {
257257
blue: {fg: 'white', bg: 'bgBlue'},
258258
gray: {fg: 'white', bg: 'bgGray'},
259259
green: {fg: 'black', bg: 'bgGreen'},
@@ -265,9 +265,9 @@ h.badge = function(s, color) {
265265
s = ' ' + s + ' ';
266266
if (color === 'random')
267267
color = _.chain(COLORS).keys().sample().value();
268-
var c = COLORS[color || 'blue'];
268+
const c = COLORS[color || 'blue'];
269269

270-
var chalk = require('./chalk');
270+
const chalk = require('./chalk');
271271
return chalk[c.fg][c.bg](s);
272272
};
273273

‎lib/icon.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ var _ = require('underscore');
33

44
var h = require('./helper');
55

6-
var icons = {
6+
const icons = {
77
yes: '✔',
88
no: '✘',
99
like: '★',
@@ -15,8 +15,8 @@ var icons = {
1515
};
1616

1717
icons.setTheme = function(name) {
18-
var defaultName = h.isWindows() ? 'win7' : 'default';
19-
var theme = this.themes[name] || this.themes[defaultName] || {};
18+
const defaultName = h.isWindows() ? 'win7' : 'default';
19+
const theme = this.themes[name] || this.themes[defaultName] || {};
2020
_.extendOwn(this, theme);
2121
};
2222

‎lib/log.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ var sprintf = require('sprintf-js').sprintf;
44

55
var chalk = require('./chalk');
66

7-
var log = {
7+
const log = {
88
output: _.bind(console.log, console),
99
level: null,
1010
levels: {
@@ -37,15 +37,13 @@ log.init = function() {
3737

3838
_.keys(this.levels).forEach(function(name) {
3939
log[name.toLowerCase()] = function() {
40-
var level = log.levels[name];
40+
const level = log.levels[name];
4141
if (log.level.value > level.value) return;
4242

43-
var args = _.toArray(arguments);
43+
const args = _.toArray(arguments);
4444
if (name !== 'INFO') args.unshift('[' + name + ']');
4545

46-
var s = args.map(function(arg) {
47-
return arg.toString();
48-
}).join(' ');
46+
let s = args.map(function(arg) { return arg.toString(); }).join(' ');
4947
if (level.color) s = chalk[level.color](s);
5048

5149
this.output(s);

‎lib/plugin.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ Plugin.prototype.setNext = function(next) {
3737
Plugin.prototype.install = function(cb) {
3838
if (this.deps.length === 0) return cb();
3939

40-
var cmd = 'npm install --save ' + this.deps.join(' ');
40+
const cmd = 'npm install --save ' + this.deps.join(' ');
4141
log.debug(cmd);
42-
var spin = h.spin(cmd);
42+
const spin = h.spin(cmd);
4343
cp.exec(cmd, {cwd: h.getCodeDir()}, function() {
4444
spin.stop();
4545
return cb();
@@ -51,9 +51,9 @@ Plugin.prototype.help = function() {};
5151
Plugin.plugins = [];
5252

5353
Plugin.init = function(head) {
54-
var plugins = [];
54+
let plugins = [];
5555
h.getCodeDirData('lib/plugins').forEach(function(f) {
56-
var p = f.data;
56+
const p = f.data;
5757
if (!p) return;
5858

5959
p.file = f.file;
@@ -76,7 +76,7 @@ Plugin.init = function(head) {
7676
return -p.id;
7777
});
7878

79-
var last = head;
79+
let last = head;
8080
plugins.forEach(function(p) {
8181
if (!p.enabled) return;
8282
last.setNext(p);
@@ -90,9 +90,9 @@ Plugin.copy = function(src, cb) {
9090
if (path.extname(src) !== '.js') {
9191
src = config.sys.urls.plugin.replace('$name', src);
9292
}
93-
var dst = h.getPluginFile(src);
93+
const dst = h.getPluginFile(src);
9494

95-
var srcstream = src.startsWith('https://') ? request(src) : fs.createReadStream(src);
95+
const srcstream = src.startsWith('https://') ? request(src) : fs.createReadStream(src);
9696
srcstream.on('response', function(resp) {
9797
if (resp.statusCode !== 200)
9898
srcstream.emit('error', 'HTTP Error: ' + resp.statusCode);
@@ -103,14 +103,14 @@ Plugin.copy = function(src, cb) {
103103
return cb(e);
104104
});
105105

106-
var dststream = fs.createWriteStream(dst);
106+
const dststream = fs.createWriteStream(dst);
107107
dststream.on('close', function() {
108108
spin.stop();
109109
return cb(null, dst);
110110
});
111111

112112
log.debug('copying from ' + src);
113-
var spin = h.spin('Downloading ' + src);
113+
const spin = h.spin('Downloading ' + src);
114114
srcstream.pipe(dststream);
115115
};
116116

@@ -119,7 +119,7 @@ Plugin.install = function(name, cb) {
119119
if (e) return log.error(e);
120120
log.debug('copied to ' + fullpath);
121121

122-
var plugin = require(fullpath);
122+
const plugin = require(fullpath);
123123
plugin.install(function() {
124124
return cb(null, plugin);
125125
});

‎lib/plugins/cache.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ var log = require('../log');
77
var Plugin = require('../plugin');
88
var session = require('../session');
99

10-
var plugin = new Plugin(50, 'cache', '', 'Plugin to provide local cache.');
10+
const plugin = new Plugin(50, 'cache', '', 'Plugin to provide local cache.');
1111

1212
plugin.init = function() {
1313
Plugin.prototype.init.call(this);
1414
cache.init();
1515
};
1616

1717
plugin.getProblems = function(cb) {
18-
var problems = cache.get(h.KEYS.problems);
18+
const problems = cache.get(h.KEYS.problems);
1919
if (problems) {
2020
log.debug('cache hit: problems.json');
2121
return cb(null, problems);
@@ -30,8 +30,8 @@ plugin.getProblems = function(cb) {
3030
};
3131

3232
plugin.getProblem = function(problem, cb) {
33-
var k = h.KEYS.problem(problem);
34-
var _problem = cache.get(k);
33+
const k = h.KEYS.problem(problem);
34+
const _problem = cache.get(k);
3535
if (_problem) {
3636
log.debug('cache hit: ' + k + '.json');
3737
_.extendOwn(problem, _problem);
@@ -50,15 +50,15 @@ plugin.saveProblem = function(problem) {
5050
// it would be better to leave specific problem cache being user
5151
// independent, thus try to reuse existing cache as much as possible
5252
// after changing user.
53-
var _problem = _.omit(problem, ['locked', 'state', 'starred']);
53+
const _problem = _.omit(problem, ['locked', 'state', 'starred']);
5454
return cache.set(h.KEYS.problem(problem), _problem);
5555
};
5656

5757
plugin.updateProblem = function(problem, kv) {
58-
var problems = cache.get(h.KEYS.problems);
58+
const problems = cache.get(h.KEYS.problems);
5959
if (!problems) return false;
6060

61-
var _problem = problems.find(function(x) { return x.id === problem.id; });
61+
const _problem = problems.find(function(x) { return x.id === problem.id; });
6262
if (!_problem) return false;
6363

6464
_.extend(_problem, kv);

‎lib/plugins/leetcode.js

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ var Plugin = require('../plugin');
1313
var Queue = require('../queue');
1414
var session = require('../session');
1515

16-
var plugin = new Plugin(10, 'leetcode', '',
16+
const plugin = new Plugin(10, 'leetcode', '',
1717
'Plugin to talk with leetcode APIs.');
1818

1919
var spin;
@@ -27,7 +27,7 @@ function signOpts(opts, user) {
2727
}
2828

2929
function makeOpts(url) {
30-
var opts = {};
30+
const opts = {};
3131
opts.url = url;
3232
opts.headers = {};
3333

@@ -38,7 +38,7 @@ function makeOpts(url) {
3838

3939
function checkError(e, resp, expectedStatus) {
4040
if (!e && resp && resp.statusCode !== expectedStatus) {
41-
var code = resp.statusCode;
41+
const code = resp.statusCode;
4242
log.debug('http error: ' + code);
4343

4444
if (code === 403 || code === 401) {
@@ -52,8 +52,8 @@ function checkError(e, resp, expectedStatus) {
5252

5353
plugin.getProblems = function(cb) {
5454
log.debug('running leetcode.getProblems');
55-
var problems = [];
56-
var getCategory = function(category, queue, cb) {
55+
let problems = [];
56+
const getCategory = function(category, queue, cb) {
5757
plugin.getCategoryProblems(category, function(e, _problems) {
5858
if (e) {
5959
log.debug(category + ': failed to getProblems: ' + e.msg);
@@ -66,7 +66,7 @@ plugin.getProblems = function(cb) {
6666
};
6767

6868
spin = h.spin('Downloading problems');
69-
var q = new Queue(config.sys.categories, {}, getCategory);
69+
const q = new Queue(config.sys.categories, {}, getCategory);
7070
q.run(null, function(e) {
7171
spin.stop();
7272
return cb(e, problems);
@@ -75,14 +75,14 @@ plugin.getProblems = function(cb) {
7575

7676
plugin.getCategoryProblems = function(category, cb) {
7777
log.debug('running leetcode.getCategoryProblems: ' + category);
78-
var opts = makeOpts(config.sys.urls.problems.replace('$category', category));
78+
const opts = makeOpts(config.sys.urls.problems.replace('$category', category));
7979

8080
spin.text = 'Downloading category ' + category;
8181
request(opts, function(e, resp, body) {
8282
e = checkError(e, resp, 200);
8383
if (e) return cb(e);
8484

85-
var json = JSON.parse(body);
85+
const json = JSON.parse(body);
8686

8787
// leetcode permits anonymous access to the problem list
8888
// while we require login first to make a better experience.
@@ -91,11 +91,11 @@ plugin.getCategoryProblems = function(category, cb) {
9191
return cb(session.errors.EXPIRED);
9292
}
9393

94-
var user = session.getUser();
94+
const user = session.getUser();
9595
user.paid = json.is_paid;
9696
session.saveUser(user);
9797

98-
var problems = json.stat_status_pairs
98+
const problems = json.stat_status_pairs
9999
.filter(function(p) {
100100
return !p.stat.question__hide;
101101
})
@@ -120,10 +120,10 @@ plugin.getCategoryProblems = function(category, cb) {
120120

121121
plugin.getProblem = function(problem, cb) {
122122
log.debug('running leetcode.getProblem');
123-
var user = session.getUser();
123+
const user = session.getUser();
124124
if (problem.locked && !user.paid) return cb('failed to load locked problem!');
125125

126-
var opts = makeOpts(config.sys.urls.problem_detail);
126+
const opts = makeOpts(config.sys.urls.problem_detail);
127127
opts.headers.Origin = config.sys.urls.base;
128128
opts.headers.Referer = problem.link;
129129

@@ -146,13 +146,13 @@ plugin.getProblem = function(problem, cb) {
146146
operationName: 'getQuestionDetail'
147147
};
148148

149-
var spin = h.spin('Downloading ' + problem.slug);
149+
const spin = h.spin('Downloading ' + problem.slug);
150150
request.post(opts, function(e, resp, body) {
151151
spin.stop();
152152
e = checkError(e, resp, 200);
153153
if (e) return cb(e);
154154

155-
var q = body.data.question;
155+
const q = body.data.question;
156156
if (!q) return cb('failed to load problem!');
157157

158158
problem.totalAC = JSON.parse(q.stats).totalAccepted;
@@ -183,7 +183,7 @@ function runCode(opts, problem, cb) {
183183
typed_code: h.getFileData(problem.file)
184184
});
185185

186-
var spin = h.spin('Sending code to judge');
186+
const spin = h.spin('Sending code to judge');
187187
request(opts, function(e, resp, body) {
188188
spin.stop();
189189
e = checkError(e, resp, 200);
@@ -200,7 +200,7 @@ function runCode(opts, problem, cb) {
200200
++opts._delay;
201201
log.debug('Will retry after %d seconds...', opts._delay);
202202

203-
var reRun = _.partial(runCode, opts, problem, cb);
203+
const reRun = _.partial(runCode, opts, problem, cb);
204204
return setTimeout(reRun, opts._delay * 1000);
205205
}
206206

@@ -212,17 +212,17 @@ function runCode(opts, problem, cb) {
212212
}
213213

214214
function verifyResult(task, queue, cb) {
215-
var opts = queue.ctx.opts;
215+
const opts = queue.ctx.opts;
216216
opts.method = 'GET';
217217
opts.url = config.sys.urls.verify.replace('$id', task.id);
218218

219-
var spin = h.spin('Waiting for judge result');
219+
const spin = h.spin('Waiting for judge result');
220220
request(opts, function(e, resp, body) {
221221
spin.stop();
222222
e = checkError(e, resp, 200);
223223
if (e) return cb(e);
224224

225-
var result = JSON.parse(body);
225+
let result = JSON.parse(body);
226226
if (result.state === 'SUCCESS') {
227227
result = formatResult(result);
228228
_.extendOwn(result, task);
@@ -235,7 +235,7 @@ function verifyResult(task, queue, cb) {
235235
}
236236

237237
function formatResult(result) {
238-
var x = {
238+
const x = {
239239
ok: result.run_success,
240240
answer: result.code_answer || '',
241241
runtime: result.status_runtime || '',
@@ -269,17 +269,17 @@ function formatResult(result) {
269269

270270
plugin.testProblem = function(problem, cb) {
271271
log.debug('running leetcode.testProblem');
272-
var opts = makeOpts(config.sys.urls.test.replace('$slug', problem.slug));
272+
const opts = makeOpts(config.sys.urls.test.replace('$slug', problem.slug));
273273
opts.body = {data_input: problem.testcase};
274274

275275
runCode(opts, problem, function(e, task) {
276276
if (e) return cb(e);
277277

278-
var tasks = [
278+
const tasks = [
279279
{type: 'Actual', id: task.interpret_id},
280280
{type: 'Expected', id: task.interpret_expected_id}
281281
];
282-
var q = new Queue(tasks, {opts: opts, results: []}, verifyResult);
282+
const q = new Queue(tasks, {opts: opts, results: []}, verifyResult);
283283
q.run(null, function(e, ctx) {
284284
return cb(e, ctx.results);
285285
});
@@ -288,14 +288,14 @@ plugin.testProblem = function(problem, cb) {
288288

289289
plugin.submitProblem = function(problem, cb) {
290290
log.debug('running leetcode.submitProblem');
291-
var opts = makeOpts(config.sys.urls.submit.replace('$slug', problem.slug));
291+
const opts = makeOpts(config.sys.urls.submit.replace('$slug', problem.slug));
292292
opts.body = {judge_type: 'large'};
293293

294294
runCode(opts, problem, function(e, task) {
295295
if (e) return cb(e);
296296

297-
var tasks = [{type: 'Actual', id: task.submission_id}];
298-
var q = new Queue(tasks, {opts: opts, results: []}, verifyResult);
297+
const tasks = [{type: 'Actual', id: task.submission_id}];
298+
const q = new Queue(tasks, {opts: opts, results: []}, verifyResult);
299299
q.run(null, function(e, ctx) {
300300
return cb(e, ctx.results);
301301
});
@@ -304,15 +304,15 @@ plugin.submitProblem = function(problem, cb) {
304304

305305
plugin.getSubmissions = function(problem, cb) {
306306
log.debug('running leetcode.getSubmissions');
307-
var opts = makeOpts(config.sys.urls.submissions.replace('$slug', problem.slug));
307+
const opts = makeOpts(config.sys.urls.submissions.replace('$slug', problem.slug));
308308
opts.headers.Referer = config.sys.urls.problem.replace('$slug', problem.slug);
309309

310310
request(opts, function(e, resp, body) {
311311
e = checkError(e, resp, 200);
312312
if (e) return cb(e);
313313

314314
// FIXME: this only return the 1st 20 submissions, we should get next if necessary.
315-
var submissions = JSON.parse(body).submissions_dump;
315+
const submissions = JSON.parse(body).submissions_dump;
316316
submissions.forEach(function(submission) {
317317
submission.id = _.last(_.compact(submission.url.split('/')));
318318
});
@@ -323,13 +323,13 @@ plugin.getSubmissions = function(problem, cb) {
323323

324324
plugin.getSubmission = function(submission, cb) {
325325
log.debug('running leetcode.getSubmission');
326-
var opts = makeOpts(config.sys.urls.submission.replace('$id', submission.id));
326+
const opts = makeOpts(config.sys.urls.submission.replace('$id', submission.id));
327327

328328
request(opts, function(e, resp, body) {
329329
e = checkError(e, resp, 200);
330330
if (e) return cb(e);
331331

332-
var re = body.match(/submissionCode:\s('[^']*')/);
332+
let re = body.match(/submissionCode:\s('[^']*')/);
333333
if (re) submission.code = eval(re[1]);
334334

335335
re = body.match(/distribution_formatted:\s('[^']+')/);
@@ -340,11 +340,11 @@ plugin.getSubmission = function(submission, cb) {
340340

341341
plugin.starProblem = function(problem, starred, cb) {
342342
log.debug('running leetcode.starProblem');
343-
var opts = makeOpts();
343+
const opts = makeOpts();
344344
opts.headers.Origin = config.sys.urls.base;
345345
opts.headers.Referer = problem.link;
346346

347-
var user = session.getUser();
347+
const user = session.getUser();
348348
if (starred) {
349349
opts.url = config.sys.urls.favorites;
350350
opts.method = 'POST';
@@ -370,28 +370,28 @@ plugin.starProblem = function(problem, starred, cb) {
370370

371371
plugin.getFavorites = function(cb) {
372372
log.debug('running leetcode.getFavorites');
373-
var opts = makeOpts(config.sys.urls.favorites);
373+
const opts = makeOpts(config.sys.urls.favorites);
374374

375375
request(opts, function(e, resp, body) {
376376
e = checkError(e, resp, 200);
377377
if (e) return cb(e);
378378

379-
var favorites = JSON.parse(body);
379+
const favorites = JSON.parse(body);
380380
return cb(null, favorites);
381381
});
382382
};
383383

384384
plugin.signin = function(user, cb) {
385385
log.debug('running leetcode.signin');
386-
var spin = h.spin('Signing in leetcode.com');
386+
const spin = h.spin('Signing in leetcode.com');
387387
request(config.sys.urls.login, function(e, resp, body) {
388388
spin.stop();
389389
e = checkError(e, resp, 200);
390390
if (e) return cb(e);
391391

392392
user.loginCSRF = h.getSetCookieValue(resp, 'csrftoken');
393393

394-
var opts = {
394+
const opts = {
395395
url: config.sys.urls.login,
396396
headers: {
397397
Origin: config.sys.urls.base,
@@ -420,7 +420,7 @@ plugin.getUser = function(user, cb) {
420420
plugin.getFavorites(function(e, favorites) {
421421
if (e) return cb(e);
422422

423-
var favorite = favorites.favorites.private_favorites.find(function(f) {
423+
const favorite = favorites.favorites.private_favorites.find(function(f) {
424424
return f.name === 'Favorite';
425425
});
426426
user.hash = favorite.id_hash;

‎lib/plugins/retry.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ var session = require('../session');
99
var plugin = new Plugin(30, 'retry', '',
1010
'Plugin to retry last failed request if autologin.enable is on.');
1111

12-
var count = {};
12+
const count = {};
1313

1414
function canRetry(e, name) {
1515
return e && config.autologin.enable && (e === session.errors.EXPIRED) && count[name] < 1;
1616
}
1717

1818
plugin.init = function() {
19-
var names = [
19+
const names = [
2020
'getProblems',
2121
'getProblem',
2222
'getSubmissions',
@@ -30,12 +30,12 @@ plugin.init = function() {
3030
names.forEach(function(name) {
3131
count[name] = 0;
3232
plugin[name] = function() {
33-
var args = _.toArray(arguments);
34-
var cb = args.pop();
33+
const args = _.toArray(arguments);
34+
const cb = args.pop();
3535

36-
var _cb = function() {
37-
var results = _.toArray(arguments);
38-
var e = results[0];
36+
const _cb = function() {
37+
const results = _.toArray(arguments);
38+
const e = results[0];
3939
if (!canRetry(e, name)) {
4040
count[name] = 0;
4141
return cb.apply(null, results);
@@ -48,7 +48,7 @@ plugin.init = function() {
4848
});
4949
};
5050

51-
var next = plugin.next;
51+
const next = plugin.next;
5252
next[name].apply(next, args.concat(_cb));
5353
};
5454
});
@@ -61,7 +61,7 @@ plugin.init = function() {
6161
plugin.relogin = function(cb) {
6262
log.debug('session expired, try to re-login...');
6363

64-
var user = session.getUser();
64+
const user = session.getUser();
6565
if (!user) {
6666
log.debug('relogin failed: no user found, please login again');
6767
return cb();

‎lib/queue.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ Queue.prototype.run = function(concurrency, onDone) {
2424
this.concurrency = concurrency || config.network.concurrency || 1;
2525
this.onDone = onDone;
2626

27-
var self = this;
28-
for (var i = 0; i < this.concurrency; ++i) {
27+
const self = this;
28+
for (let i = 0; i < this.concurrency; ++i) {
2929
setImmediate(function() { self.workerRun(); });
3030
}
3131
};
@@ -38,8 +38,8 @@ Queue.prototype.workerRun = function() {
3838
return;
3939
}
4040

41-
var task = this.tasks.shift();
42-
var self = this;
41+
const task = this.tasks.shift();
42+
const self = this;
4343
this.onTask(task, self, function(e) {
4444
if (e) self.error = e;
4545

‎lib/session.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ var cache = require('./cache');
66
var config = require('./config');
77
var h = require('./helper');
88

9-
var session = {};
9+
const session = {};
1010

1111
session.errors = {
1212
EXPIRED: {
@@ -22,7 +22,7 @@ session.getUser = function() {
2222
session.saveUser = function(user) {
2323
// when auto login enabled, have to save password to re-login later
2424
// otherwise don't dump password for the sake of security.
25-
var _user = _.omit(user, config.autologin.enable ? [] : ['pass']);
25+
const _user = _.omit(user, config.autologin.enable ? [] : ['pass']);
2626
cache.set(h.KEYS.user, _user);
2727
};
2828

@@ -36,9 +36,9 @@ session.isLogin = function() {
3636

3737
session.updateStat = function(k, v) {
3838
// TODO: use other storage if too many stat data
39-
var today = moment().format('YYYY-MM-DD');
40-
var stats = cache.get(h.KEYS.stat) || {};
41-
var stat = stats[today] = stats[today] || {};
39+
const today = moment().format('YYYY-MM-DD');
40+
const stats = cache.get(h.KEYS.stat) || {};
41+
const stat = stats[today] = stats[today] || {};
4242
stat[k] = stat[k] || 0;
4343
stat[k] += v;
4444
cache.set(h.KEYS.stat, stats);

0 commit comments

Comments
 (0)
Please sign in to comment.