Skip to content

Commit

Permalink
Fix types to allow literal nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Mar 18, 2022
1 parent 2810a31 commit fced791
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
14 changes: 8 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
/**
* @typedef {import('unist').Node} Node
* @typedef {import('unist').Parent} Parent
* @typedef {import('unist').Position} Position
* @typedef {import('unist').Node} Node
* @typedef {Record<string, unknown> & {type: string, position?: Position|undefined}} NodeLike
*/

/**
* Function called with a node to produce a new node.
*
* @callback MapFunction
* @param {Node} node Current node being processed
* @param {NodeLike|Node} node Current node being processed
* @param {number} [index] Index of `node`, or `null`
* @param {Parent} [parent] Parent of `node`, or `null`
* @returns {Node} Node to be used in the new tree. Its children are not used: if the original node has children, those are mapped.
* @returns {NodeLike|Node} Node to be used in the new tree. Its children are not used: if the original node has children, those are mapped.
*/

/**
* Unist utility to create a new tree by mapping all nodes with the given function.
*
* @param {Node} tree Tree to map
* @param {NodeLike|Node} tree Tree to map
* @param {MapFunction} iteratee Function that returns a new node
* @returns {Node} New mapped tree.
* @returns {NodeLike|Node} New mapped tree.
*/
export function map(tree, iteratee) {
return preorder(tree, null, null)

/**
* @param {Node} node
* @param {NodeLike|Node} node
* @param {number} [index]
* @param {Parent} [parent]
* @returns {Node}
Expand Down
15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@ test('unist-util-map', function (t) {
'should map the specified node'
)

t.deepEqual(
map(
{
type: 'root',
children: [
{type: 'node', children: [{type: 'leaf', value: '1'}]},
{type: 'leaf', value: '2'}
]
},
changeLeaf
),
u('root', [u('node', [u('leaf', 'CHANGED')]), u('leaf', 'CHANGED')]),
'should map the specified node'
)

t.deepEqual(
map(u('root', [u('node', [u('leaf', '1')]), u('leaf', '2')]), nullLeaf),
// @ts-expect-error: not valid but tested anyway.
Expand Down

0 comments on commit fced791

Please sign in to comment.