2
2
* @typedef {import('unist').Node } Node
3
3
* @typedef {import('unist-util-visit').Test } Test
4
4
*
5
- * @typedef {(node: Node) => unknown } KeyFunction
5
+ * @callback KeyFunction
6
+ * Function called with every added node (`Node`) to calculate the key to
7
+ * index on.
8
+ * @param {Node } node
9
+ * Node to calculate a key for.
10
+ * @returns {unknown }
11
+ * Key to index on.
12
+ * Can be anything that can be used as a key in a `Map`.
6
13
*/
7
14
8
15
import { visit } from 'unist-util-visit'
9
16
10
17
export class Index {
11
18
/**
19
+ * Create a mutable index data structure, that maps property values or
20
+ * computed keys, to nodes.
21
+ *
22
+ * If `tree` is given, the index is initialized with all nodes, optionally
23
+ * filtered by `test`.
24
+ *
12
25
* @param {string|KeyFunction } prop
26
+ * Field (`string`) to look up in each node to find keys or function called
27
+ * with each node to calculate keys.
13
28
* @param {Node } [tree]
29
+ * Tree to index.
14
30
* @param {Test } [test]
31
+ * `is`-compatible test.
15
32
*/
16
33
constructor ( prop , tree , test ) {
17
34
/** @type {Map<unknown, Array<Node>> } */
@@ -28,15 +45,25 @@ export class Index {
28
45
}
29
46
30
47
/**
48
+ * Get nodes by `key`.
49
+ *
31
50
* @param {unknown } key
51
+ * Key to retrieve.
52
+ * Can be anything that can be used as a key in a `Map`.
32
53
* @returns {Array<Node> }
54
+ * List of zero or more nodes.
33
55
*/
34
56
get ( key ) {
35
57
return this . index . get ( key ) || [ ]
36
58
}
37
59
38
60
/**
61
+ * Add `node` to the index (if not already present).
62
+ *
39
63
* @param {Node } node
64
+ * Node to index.
65
+ * @returns
66
+ * Current instance.
40
67
*/
41
68
add ( node ) {
42
69
const key = this . key ( node )
@@ -55,7 +82,12 @@ export class Index {
55
82
}
56
83
57
84
/**
85
+ * Remove `node` from the index (if present).
86
+ *
58
87
* @param {Node } node
88
+ * Node to remove.
89
+ * @returns
90
+ * Current instance.
59
91
*/
60
92
remove ( node ) {
61
93
const key = this . key ( node )
0 commit comments