0.1.1 • Published 1 year ago
unist-util-map-postorder v0.1.1
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 andtree
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
orunist-util-reduce
.
- This feature can also be archived using
- Also exported a
mapAsync
that supports async function.
Related
unist-util-map
— create a new tree with all nodes mapped by a given functionunist-util-reduce
- recursively reduce a treeunist-util-flatmap
— create a new tree by expanding a node into manyunist-util-filter
— create a new tree with all nodes that pass the given functionunist-util-remove
— remove nodes from treesunist-util-select
— select nodes with CSS-like selectorsunist-util-visit
— walk treesunist-builder
— create trees