|
1 | 1 | /** |
2 | | - * @typedef {import('unist').Parent} Parent |
3 | | - * @typedef {import('unist').Position} Position |
4 | 2 | * @typedef {import('unist').Node} Node |
5 | | - * @typedef {Record<string, unknown> & {type: string, position?: Position|undefined}} NodeLike |
6 | | - */ |
7 | | - |
8 | | -/** |
9 | | - * Function called with a node to produce a new node. |
10 | | - * |
11 | | - * @callback MapFunction |
12 | | - * @param {NodeLike|Node} node Current node being processed |
13 | | - * @param {number} [index] Index of `node`, or `null` |
14 | | - * @param {Parent} [parent] Parent of `node`, or `null` |
15 | | - * @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. |
16 | 3 | */ |
17 | 4 |
|
18 | 5 | /** |
19 | 6 | * Unist utility to create a new tree by mapping all nodes with the given function. |
20 | 7 | * |
21 | | - * @param {NodeLike|Node} tree Tree to map |
22 | | - * @param {MapFunction} iteratee Function that returns a new node |
23 | | - * @returns {NodeLike|Node} New mapped tree. |
| 8 | + * @template {Node} Tree |
| 9 | + * @param {Tree} tree Tree to map |
| 10 | + * @param {import('./complex-types').MapFunction<Tree>} iteratee Function that returns a new node |
| 11 | + * @returns {Tree} New mapped tree. |
24 | 12 | */ |
25 | 13 | export function map(tree, iteratee) { |
| 14 | + // @ts-expect-error Looks like a children. |
26 | 15 | return preorder(tree, null, null) |
27 | 16 |
|
28 | | - /** |
29 | | - * @param {NodeLike|Node} node |
30 | | - * @param {number} [index] |
31 | | - * @param {Parent} [parent] |
32 | | - * @returns {Node} |
33 | | - */ |
| 17 | + /** @type {import('./complex-types').MapFunction<Tree>} */ |
34 | 18 | function preorder(node, index, parent) { |
35 | 19 | var newNode = Object.assign({}, iteratee(node, index, parent)) |
36 | 20 |
|
37 | 21 | if ('children' in node) { |
38 | 22 | // @ts-expect-error Looks like a parent. |
39 | 23 | newNode.children = node.children.map(function ( |
40 | | - /** @type {Node} */ child, |
| 24 | + /** @type {import('./complex-types').InclusiveDescendant<Tree>} */ child, |
41 | 25 | /** @type {number} */ index |
42 | 26 | ) { |
43 | | - // @ts-expect-error Looks like a parent. |
44 | 27 | return preorder(child, index, node) |
45 | 28 | }) |
46 | 29 | } |
|
0 commit comments