Skip to content

Commit e5699df

Browse files
authored
Modernize some code (avajs#1876)
Some things XO wouldn't catch.
1 parent c4f607c commit e5699df

14 files changed

+89
-96
lines changed

Diff for: bench/compare.js

+34-35
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,14 @@ const results = {};
5757
const fileNames = files.map(file => file['.file']);
5858
const stats = ['mean', 'stdDev', 'median', 'min', 'max'];
5959

60-
files.forEach(file => {
60+
for (const file of files) {
6161
Object.keys(file)
62-
.filter(key => !/^\./.test(key))
62+
.filter(key => !key.startsWith('.'))
6363
.forEach(key => {
6464
results[key] = results[key] || {};
6565
results[key][file['.file']] = prepStats(file[key]);
6666
});
67-
});
67+
}
6868

6969
const table = new Table();
7070
table.push(
@@ -78,37 +78,36 @@ table.push(
7878
stats.reduce(arr => arr.concat(fileNames), ['args'])
7979
);
8080

81-
Object.keys(results)
82-
.forEach(key => {
83-
table.push(stats.reduce((arr, stat) => {
84-
let min = Infinity;
85-
let max = -Infinity;
86-
87-
const statGroup = fileNames.map(fileName => {
88-
let result = results[key][fileName];
89-
result = result && result[stat];
90-
91-
if (result) {
92-
min = Math.min(min, result);
93-
max = Math.max(max, result);
94-
return result;
95-
}
96-
97-
return '';
98-
});
99-
100-
return arr.concat(statGroup.map(stat => {
101-
if (stat === min) {
102-
return chalk.green(stat);
103-
}
104-
105-
if (stat === max) {
106-
return chalk.red(stat);
107-
}
108-
109-
return stat;
110-
}));
111-
}, [key]));
112-
});
81+
for (const key of Object.keys(results)) {
82+
table.push(stats.reduce((arr, stat) => {
83+
let min = Infinity;
84+
let max = -Infinity;
85+
86+
const statGroup = fileNames.map(fileName => {
87+
let result = results[key][fileName];
88+
result = result && result[stat];
89+
90+
if (result) {
91+
min = Math.min(min, result);
92+
max = Math.max(max, result);
93+
return result;
94+
}
95+
96+
return '';
97+
});
98+
99+
return arr.concat(statGroup.map(stat => {
100+
if (stat === min) {
101+
return chalk.green(stat);
102+
}
103+
104+
if (stat === max) {
105+
return chalk.red(stat);
106+
}
107+
108+
return stat;
109+
}));
110+
}, [key]));
111+
}
113112

114113
console.log(table.toString());

Diff for: docs/recipes/when-to-use-plan.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ In most cases, it's a bad idea to use any complex branching inside your tests. A
119119
```js
120120
const testData = require('./fixtures/test-definitions.json');
121121

122-
testData.forEach(testDefinition => {
122+
for (const testDefinition of testData) {
123123
test('foo or bar', t => {
124124
const result = functionUnderTest(testDefinition.input);
125125

@@ -134,7 +134,7 @@ testData.forEach(testDefinition => {
134134
t.is(result.bar, testDefinition.foo);
135135
}
136136
});
137-
});
137+
}
138138
```
139139

140140
## Conclusion

Diff for: lib/ava-files.js

+7-7
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ class AvaFiles {
158158
const overrideDefaultIgnorePatterns = [];
159159

160160
let hasPositivePattern = false;
161-
this.sources.forEach(pattern => {
161+
for (const pattern of this.sources) {
162162
mixedPatterns.push(pattern);
163163

164164
// TODO: Why not just `pattern[0] !== '!'`?
@@ -168,10 +168,10 @@ class AvaFiles {
168168

169169
// Extract patterns that start with an ignored directory. These need to be
170170
// rematched separately.
171-
if (defaultIgnore.indexOf(pattern.split('/')[0]) >= 0) {
171+
if (defaultIgnore.includes(pattern.split('/')[0])) {
172172
overrideDefaultIgnorePatterns.push(pattern);
173173
}
174-
});
174+
}
175175

176176
// Same defaults as used for Chokidar
177177
if (!hasPositivePattern) {
@@ -182,7 +182,7 @@ class AvaFiles {
182182

183183
// Ignore paths outside the current working directory.
184184
// They can't be matched to a pattern.
185-
if (/^\.\.\//.test(filePath)) {
185+
if (filePath.startsWith('../')) {
186186
return false;
187187
}
188188

@@ -255,21 +255,21 @@ class AvaFiles {
255255
let paths = [];
256256
let ignored = [];
257257

258-
this.sources.forEach(pattern => {
258+
for (const pattern of this.sources) {
259259
if (pattern[0] === '!') {
260260
ignored.push(pattern.slice(1));
261261
} else {
262262
paths.push(pattern);
263263
}
264-
});
264+
}
265265

266266
// Allow source patterns to override the default ignore patterns. Chokidar
267267
// ignores paths that match the list of ignored patterns. It uses anymatch
268268
// under the hood, which supports negation patterns. For any source pattern
269269
// that starts with an ignored directory, ensure the corresponding negation
270270
// pattern is added to the ignored paths.
271271
const overrideDefaultIgnorePatterns = paths
272-
.filter(pattern => defaultIgnore.indexOf(pattern.split('/')[0]) >= 0)
272+
.filter(pattern => defaultIgnore.includes(pattern.split('/')[0]))
273273
.map(pattern => `!${pattern}`);
274274

275275
ignored = getDefaultIgnorePatterns().concat(ignored, overrideDefaultIgnorePatterns);

Diff for: lib/serialize-error.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ function buildSource(source) {
3939
const rel = path.relative(projectDir, file);
4040

4141
const isWithinProject = rel.split(path.sep)[0] !== '..';
42-
const isDependency = isWithinProject && path.dirname(rel).split(path.sep).indexOf('node_modules') > -1;
42+
const isDependency = isWithinProject && path.dirname(rel).split(path.sep).includes('node_modules');
4343

4444
return {
4545
isDependency,

Diff for: lib/watcher.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class TestDependency {
7373
}
7474

7575
contains(source) {
76-
return this.sources.indexOf(source) !== -1;
76+
return this.sources.includes(source);
7777
}
7878
}
7979

@@ -97,7 +97,7 @@ class Watcher {
9797

9898
let runOnlyExclusive = false;
9999
if (specificFiles) {
100-
const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.indexOf(file) !== -1);
100+
const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.includes(file));
101101
runOnlyExclusive = exclusiveFiles.length !== this.filesWithExclusiveTests.length;
102102
if (runOnlyExclusive) {
103103
// The test files that previously contained exclusive tests are always
@@ -294,21 +294,21 @@ class Watcher {
294294
sumPreviousFailures(beforeVector) {
295295
let total = 0;
296296

297-
this.filesWithFailures.forEach(state => {
297+
for (const state of this.filesWithFailures) {
298298
if (state.vector < beforeVector) {
299299
total += state.count;
300300
}
301-
});
301+
}
302302

303303
return total;
304304
}
305305

306306
cleanUnlinkedTests(unlinkedTests) {
307-
unlinkedTests.forEach(testFile => {
307+
for (const testFile of unlinkedTests) {
308308
this.updateTestDependencies(testFile, []);
309309
this.updateExclusivity(testFile, false);
310310
this.pruneFailures([testFile]);
311-
});
311+
}
312312
}
313313

314314
observeStdin(stdin) {

Diff for: lib/worker/dependency-tracker.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function track(filename) {
2828
exports.track = track;
2929

3030
function install(testPath) {
31-
Object.keys(require.extensions).forEach(ext => {
31+
for (const ext of Object.keys(require.extensions)) {
3232
const wrappedHandler = require.extensions[ext];
3333

3434
require.extensions[ext] = (module, filename) => {
@@ -38,6 +38,6 @@ function install(testPath) {
3838

3939
wrappedHandler(module, filename);
4040
};
41-
});
41+
}
4242
}
4343
exports.install = install;

Diff for: lib/worker/subprocess.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,11 @@ runner.on('finish', () => {
6969
}
7070

7171
nowAndTimers.setImmediate(() => {
72-
currentlyUnhandled().filter(rejection => {
73-
return !attributedRejections.has(rejection.promise);
74-
}).forEach(rejection => {
75-
ipc.send({type: 'unhandled-rejection', err: serializeError('Unhandled rejection', true, rejection.reason)});
76-
});
72+
currentlyUnhandled()
73+
.filter(rejection => !attributedRejections.has(rejection.promise))
74+
.forEach(rejection => {
75+
ipc.send({type: 'unhandled-rejection', err: serializeError('Unhandled rejection', true, rejection.reason)});
76+
});
7777

7878
exit(0);
7979
});
@@ -103,15 +103,15 @@ dependencyTracking.install(testPath);
103103
precompilerHook.install();
104104

105105
try {
106-
(options.require || []).forEach(x => {
107-
const required = require(x);
106+
for (const mod of (options.require || [])) {
107+
const required = require(mod);
108108

109109
try {
110110
if (required[Symbol.for('esm\u200D:package')]) {
111111
require = required(module); // eslint-disable-line no-global-assign
112112
}
113113
} catch (_) {}
114-
});
114+
}
115115

116116
require(testPath);
117117

Diff for: test/api.js

+3-11
Original file line numberDiff line numberDiff line change
@@ -627,18 +627,10 @@ test('caching is enabled by default', t => {
627627
return api.run([path.join(__dirname, 'fixture/caching/test.js')])
628628
.then(() => {
629629
const files = fs.readdirSync(path.join(__dirname, 'fixture/caching/node_modules/.cache/ava'));
630-
t.is(files.filter(x => endsWithJs(x)).length, 1);
631-
t.is(files.filter(x => endsWithMap(x)).length, 1);
630+
t.is(files.filter(x => x.endsWith('.js')).length, 1);
631+
t.is(files.filter(x => x.endsWith('.map')).length, 1);
632632
t.is(files.length, 2);
633633
});
634-
635-
function endsWithJs(filename) {
636-
return /\.js$/.test(filename);
637-
}
638-
639-
function endsWithMap(filename) {
640-
return /\.map$/.test(filename);
641-
}
642634
});
643635

644636
test('caching can be disabled', t => {
@@ -702,7 +694,7 @@ test('emits dependencies for test files', t => {
702694
api.on('run', plan => {
703695
plan.status.on('stateChange', evt => {
704696
if (evt.type === 'dependencies') {
705-
t.notEqual(testFiles.indexOf(evt.testFile), -1);
697+
t.true(testFiles.includes(evt.testFile));
706698
t.strictDeepEqual(evt.dependencies.slice(-3), sourceFiles);
707699
}
708700
});

Diff for: test/fixture/debug-arg.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import test from '../..';
22

33
test('test', t => {
4-
t.true(process.execArgv[0].indexOf('--debug') === 0);
4+
t.true(process.execArgv[0].startsWith('--debug'));
55
});

Diff for: test/fixture/inspect-arg.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import test from '../..';
22

33
test('test', t => {
4-
t.true(process.execArgv[0].indexOf('--inspect') === 0);
4+
t.true(process.execArgv[0].startsWith('--inspect'));
55
});

Diff for: test/integration/assorted.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ test('--match works', t => {
3030
});
3131
});
3232

33-
['--tap', '-t'].forEach(tapFlag => {
33+
for (const tapFlag of ['--tap', '-t']) {
3434
test(`${tapFlag} should produce TAP output`, t => {
3535
execCli([tapFlag, 'test.js'], {dirname: 'fixture/watcher'}, err => {
3636
t.ok(!err);
3737
t.end();
3838
});
3939
});
40-
});
40+
}
4141

4242
test('handles NODE_PATH', t => {
4343
const nodePaths = `node-paths/modules${path.delimiter}node-paths/deep/nested`;

Diff for: test/integration/concurrency.js

+12-10
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,53 @@
22
const test = require('tap').test;
33
const {execCli} = require('../helper/cli');
44

5-
['--concurrency', '-c'].forEach(concurrencyFlag => {
5+
const concurrencyFlags = ['--concurrency', '-c'];
6+
7+
for (const concurrencyFlag of concurrencyFlags) {
68
test(`bails when ${concurrencyFlag} is provided without value`, t => {
79
execCli(['test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
810
t.is(err.code, 1);
911
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
1012
t.end();
1113
});
1214
});
13-
});
15+
}
1416

15-
['--concurrency', '-c'].forEach(concurrencyFlag => {
17+
for (const concurrencyFlag of concurrencyFlags) {
1618
test(`bails when ${concurrencyFlag} is provided with an input that is a string`, t => {
1719
execCli([`${concurrencyFlag}=foo`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
1820
t.is(err.code, 1);
1921
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
2022
t.end();
2123
});
2224
});
23-
});
25+
}
2426

25-
['--concurrency', '-c'].forEach(concurrencyFlag => {
27+
for (const concurrencyFlag of concurrencyFlags) {
2628
test(`bails when ${concurrencyFlag} is provided with an input that is a float`, t => {
2729
execCli([`${concurrencyFlag}=4.7`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
2830
t.is(err.code, 1);
2931
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
3032
t.end();
3133
});
3234
});
33-
});
35+
}
3436

35-
['--concurrency', '-c'].forEach(concurrencyFlag => {
37+
for (const concurrencyFlag of concurrencyFlags) {
3638
test(`bails when ${concurrencyFlag} is provided with an input that is negative`, t => {
3739
execCli([`${concurrencyFlag}=-1`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
3840
t.is(err.code, 1);
3941
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
4042
t.end();
4143
});
4244
});
43-
});
45+
}
4446

45-
['--concurrency', '-c'].forEach(concurrencyFlag => {
47+
for (const concurrencyFlag of concurrencyFlags) {
4648
test(`works when ${concurrencyFlag} is provided with a value`, t => {
4749
execCli([`${concurrencyFlag}=1`, 'test.js'], {dirname: 'fixture/concurrency'}, err => {
4850
t.ifError(err);
4951
t.end();
5052
});
5153
});
52-
});
54+
}

0 commit comments

Comments
 (0)