You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
876 B
JavaScript

"use strict";
const isIterable = require("is-iterable");
const map = require("../map");
// FIXME: Untested
module.exports = function treeMap(tree, mapper, options = {}) {
let key = options.key ?? "children";
function step(subtree) {
let mapped = mapper(subtree);
let modifiedProperties = {};
if (isIterable(mapped[key])) {
modifiedProperties[key] = mapped[key].map((item) => step(item));
} else if (mapped[key] != null && typeof mapped[key] === "object") {
modifiedProperties[key] = step(mapped[key]);
}
// We track modified properties separately and (immutably) merge them at the end, because it's the fastest way to ensure that we don't mutate the input object under any circumstances (even after we add multi-key support)
return {
... mapped,
... modifiedProperties
};
}
return isIterable(tree)
? map(tree, step)
: step(tree);
};