From 956b9cb5e0fc562257cadf35a94befa3a999f89f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9e=20Kooi?= Date: Wed, 18 Apr 2018 16:58:46 +0200 Subject: [PATCH] Skip parsing if file doesn't contain assertions 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. --- index.js | 11 +++++++++-- test/fixtures/func/no-assert.js | 1 + test/test.js | 11 +++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 test/fixtures/func/no-assert.js diff --git a/index.js b/index.js index 5b88068..74502d1 100644 --- a/index.js +++ b/index.js @@ -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(); @@ -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); } diff --git a/test/fixtures/func/no-assert.js b/test/fixtures/func/no-assert.js new file mode 100644 index 0000000..f6c9369 --- /dev/null +++ b/test/fixtures/func/no-assert.js @@ -0,0 +1 @@ +contains some invalid code to make sure that this did not get parsed diff --git a/test/test.js b/test/test.js index 0177427..c3c7eae 100644 --- a/test/test.js +++ b/test/test.js @@ -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(); + })); + }); });