Skip to content

Commit 622b682

Browse files
committed
Optimize flattenContent to avoid repeated array spreading
1 parent f61447c commit 622b682

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

src/utilities/content-utils.mjs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,24 @@ export const walkContent = (tree, callback) => {
2121
* @return {array} - A flattened list of leaf node descendants
2222
*/
2323
export const flattenContent = (tree) => {
24-
if (tree.children) {
25-
return tree.children.reduce(
26-
(flat, item) => [
27-
...flat,
28-
...(Array.isArray(item.children) ? flattenContent(item) : [item]),
29-
],
30-
[],
31-
);
24+
const flat = [];
25+
const walk = (node) => {
26+
if (node && Array.isArray(node.children)) {
27+
for (const child of node.children) {
28+
walk(child);
29+
}
30+
} else {
31+
flat.push(node);
32+
}
33+
};
34+
35+
if (tree && Array.isArray(tree.children)) {
36+
for (const child of tree.children) {
37+
walk(child);
38+
}
3239
}
33-
return [];
40+
41+
return flat;
3442
};
3543

3644
/**

0 commit comments

Comments
 (0)