Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@
* @typedef {import('unist').Node} Node
*/

/**
* @template {Node} [Tree=Node]
* @typedef {import('./complex-types.js').MapFunction<Tree>} MapFunction
* Function called with a node, its index, and its parent to produce a new
* node.
*/

/**
* Create a new tree by mapping all nodes with the given function.
*
* @template {Node} Tree
* Type of input tree.
* @param {Tree} tree
* Tree to map.
* @param {import('./complex-types').MapFunction<Tree>} mapFunction
* @param {MapFunction<Tree>} mapFunction
* Function called with a node, its index, and its parent to produce a new
* node.
* @returns {Tree}
Expand Down
3 changes: 1 addition & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,7 @@ if the original node has children, those are mapped instead.
## Types

This package is fully typed with [TypeScript][].
It exports a type `MapFunction<Tree extends Node = Node>` from
`unist-util-map/complex-types.d.ts` to properly type `MapFunction`s.
It exports a type `MapFunction<Tree extends Node = Node>` to properly type `MapFunction`s.

## Compatibility

Expand Down
16 changes: 16 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ test('unist-util-map', function (t) {
'should work when passing an empty object'
)

/** @type {Root} */
const tree = u('root', [u('node', [u('leaf', '1')]), u('leaf', '2')])

t.deepEqual(
map(tree, asIs),
tree,
'should support an explicitly typed `MapFunction`'
)

t.end()

/**
Expand All @@ -69,4 +78,11 @@ test('unist-util-map', function (t) {
function addValue() {
return {value: 'test'}
}

/**
* @type {import('./index.js').MapFunction<Root>}
*/
function asIs(node) {
return node
}
})