Skip to content

Commit

Permalink
Reimplement micromark helper filterByPredicate to do fewer array mani…
Browse files Browse the repository at this point in the history
…pulations for a ~6-7% elapsed time reduction.
  • Loading branch information
DavidAnson committed Sep 3, 2023
1 parent 24c97a5 commit 6a2b867
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 18 deletions.
32 changes: 23 additions & 9 deletions demo/markdownlint-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
35 changes: 26 additions & 9 deletions helpers/micromark.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 6a2b867

Please sign in to comment.