Add (untested) tree-map-flat utility
parent
8018850aec
commit
28e61a0d83
@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
|
||||
const isIterable = require("is-iterable");
|
||||
const forEach = require("../for-each");
|
||||
|
||||
module.exports = function treeMap(tree, mapper, options = {}) {
|
||||
let key = options.key ?? "children";
|
||||
let recurseAfterMap = options.recurseAfterMap ?? false;
|
||||
|
||||
let results = [];
|
||||
|
||||
function step(subtree) {
|
||||
let mapped = mapper(subtree);
|
||||
|
||||
results.push(mapped);
|
||||
|
||||
let nextChildren = (recurseAfterMap)
|
||||
? mapped[key]
|
||||
: subtree[key];
|
||||
|
||||
if (isIterable(nextChildren)) {
|
||||
forEach(nextChildren, step);
|
||||
} else if (nextChildren != null && typeof nextChildren === "object") {
|
||||
step(nextChildren);
|
||||
}
|
||||
}
|
||||
|
||||
if (isIterable(tree)) {
|
||||
forEach(tree, step);
|
||||
} else {
|
||||
step(tree);
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
Loading…
Reference in New Issue