From 6a2b86753b567c3056855ad115ccfba66064269b Mon Sep 17 00:00:00 2001 From: David Anson Date: Sat, 2 Sep 2023 21:30:43 -0700 Subject: [PATCH] Reimplement micromark helper filterByPredicate to do fewer array manipulations for a ~6-7% elapsed time reduction. --- demo/markdownlint-browser.js | 32 +++++++++++++++++++++++--------- helpers/micromark.cjs | 35 ++++++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 18 deletions(-) diff --git a/demo/markdownlint-browser.js b/demo/markdownlint-browser.js index c1dd3656..6fc8f86e 100644 --- a/demo/markdownlint-browser.js +++ b/demo/markdownlint-browser.js @@ -1320,15 +1320,29 @@ function micromarkParse(markdown) { */ function filterByPredicate(tokens, allowed, transformChildren) { var result = []; - var pending = _toConsumableArray(tokens); - var token = null; - while (token = pending.shift()) { - if (allowed(token)) { - result.push(token); - } - if (token.children.length > 0) { - var transformed = transformChildren ? transformChildren(token) : token.children; - pending.unshift.apply(pending, _toConsumableArray(transformed)); + var queue = [{ + "array": tokens, + "index": 0 + }]; + while (queue.length > 0) { + var current = queue[queue.length - 1]; + var array = current.array, + index = current.index; + if (index < array.length) { + var token = array[current.index++]; + if (allowed(token)) { + result.push(token); + } + var children = token.children; + if (children.length > 0) { + var transformed = transformChildren ? transformChildren(token) : children; + queue.push({ + "array": transformed, + "index": 0 + }); + } + } else { + queue.pop(); } } return result; diff --git a/helpers/micromark.cjs b/helpers/micromark.cjs index 5af8165b..fcc52e34 100644 --- a/helpers/micromark.cjs +++ b/helpers/micromark.cjs @@ -213,16 +213,33 @@ function micromarkParse( */ function filterByPredicate(tokens, allowed, transformChildren) { const result = []; - const pending = [ ...tokens ]; - let token = null; - while ((token = pending.shift())) { - if (allowed(token)) { - result.push(token); + const queue = [ + { + "array": tokens, + "index": 0 } - if (token.children.length > 0) { - const transformed = - transformChildren ? transformChildren(token) : token.children; - pending.unshift(...transformed); + ]; + while (queue.length > 0) { + const current = queue[queue.length - 1]; + const { array, index } = current; + if (index < array.length) { + const token = array[current.index++]; + if (allowed(token)) { + result.push(token); + } + const { children } = token; + if (children.length > 0) { + const transformed = + transformChildren ? transformChildren(token) : children; + queue.push( + { + "array": transformed, + "index": 0 + } + ); + } + } else { + queue.pop(); } } return result;