unist-util-map-postorder
unist utility to create a new tree by mapping all nodes in postorder traversal with a given function.
Install
This package is ESM only. In Node.js, install with npm:
npm install unist-util-map-postorder
Use
import { u } from 'unist-builder';
import { map } from 'unist-util-map-postorder';
const tree = u('tree', [
u('leaf', 'leaf 1'),
u('node', [u('leaf', 'leaf 2')]),
u('void'),
u('leaf', 'leaf 3'),
]);
const next = map(tree, (node) => {
return node.type === 'leaf' ? Object.assign({}, node, { value: 'CHANGED' }) : node;
});
console.dir(next, { depth: null });
Yields:
{
type: 'tree',
children: [
{type: 'leaf', value: 'CHANGED'},
{type: 'node', children: [{type: 'leaf', value: 'CHANGED'}]},
{type: 'void'},
{type: 'leaf', value: 'CHANGED'}
]
}
Note: next
is a changed clone and tree
is not mutated.
The given function was applied in postorder traversal.
More features:
- Support replacing the original node with an array of nodes returned(E.g. replace a node by its children). Returning an empty array will delete.
- This feature can also be archived using
unist-util-flatmap
or unist-util-reduce
.
- Also exported a
mapAsync
that supports async function.
Related