Skip to content

Commit

Permalink
Skip parsing if file doesn't contain assertions
Browse files Browse the repository at this point in the history
Unassertify is quite an expensive transform, because it does full
parsing and code generation. That only needs to be done for files that
contain assertions, though. This patch adds a quick check: if the string
`assert` does not even occur in the file, we'll just skip it, saving
some time.
  • Loading branch information
goto-bus-stop committed Apr 18, 2018
1 parent 37b3ae8 commit 956b9cb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
11 changes: 9 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ function shouldProduceSourceMap (options) {
return (options && options._flags && options._flags.debug);
}

function containsAssertions (src) {
// Matches both `assert` and `power-assert`.
return src.indexOf('assert') !== -1;
}

module.exports = function unassertify (filepath, options) {
if (path.extname(filepath) === '.json') {
return through();
Expand All @@ -100,11 +105,13 @@ module.exports = function unassertify (filepath, options) {
}

function end() {
if (shouldProduceSourceMap(options)) {
if (!containsAssertions(data)) {
stream.queue(data);
} else if (shouldProduceSourceMap(options)) {
stream.queue(applyUnassertWithSourceMap(data, filepath));
} else {
stream.queue(applyUnassertWithoutSourceMap(data));
}
}
stream.queue(null);
}

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/func/no-assert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
contains some invalid code to make sure that this did not get parsed
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ describe('unassertify', function () {
done();
}));
});
it('skips files that do not contain assertions', function (done) {
var filename = path.join(__dirname, 'fixtures', 'func', 'no-assert.js');
fs.createReadStream(filename)
.pipe(unassertify(filename, {}))
.pipe(es.wait(function(err, data) {
assert(!err);
var code = data.toString('utf-8');
assert(! /assert/.test(code));
done();
}));
});
});


Expand Down

0 comments on commit 956b9cb

Please sign in to comment.