1
1
/**
2
2
* @typedef {import('unist').Node } Node
3
3
* @typedef {import('unist-util-visit').Test } Test
4
- *
4
+ */
5
+
6
+ /**
5
7
* @callback KeyFunction
6
8
* Function called with every added node (`Node`) to calculate the key to
7
9
* index on.
@@ -23,23 +25,19 @@ export class Index {
23
25
* If `tree` is given, the index is initialized with all nodes, optionally
24
26
* filtered by `test`.
25
27
*
26
- * @param {string | KeyFunction } prop
28
+ * @param {KeyFunction | string } prop
27
29
* Field (`string`) to look up in each node to find keys or function called
28
30
* with each node to calculate keys.
29
31
* @param {Node | null | undefined } [tree]
30
- * Tree to index.
32
+ * Tree to index (optional) .
31
33
* @param {Test | null | undefined } [test]
32
- * `is`-compatible test.
34
+ * `is`-compatible test (optional) .
33
35
*/
34
36
constructor ( prop , tree , test ) {
35
37
/** @type {Map<unknown, Array<Node>> } */
36
38
this . index = new Map ( )
37
39
/** @type {KeyFunction } */
38
- this . key =
39
- typeof prop === 'string'
40
- ? // @ts -expect-error: Looks indexable.
41
- /** @type {KeyFunction } */ ( ( node ) => node [ prop ] )
42
- : prop
40
+ this . key = typeof prop === 'string' ? createKeyFunction ( prop ) : prop
43
41
44
42
if ( tree ) {
45
43
visit ( tree , test , ( node ) => {
@@ -108,3 +106,18 @@ export class Index {
108
106
return this
109
107
}
110
108
}
109
+
110
+ /**
111
+ * @param {string } field
112
+ * @returns {KeyFunction }
113
+ */
114
+ function createKeyFunction ( field ) {
115
+ return keyFunction
116
+
117
+ /** @type {KeyFunction } */
118
+ function keyFunction ( node ) {
119
+ // @ts -expect-error: all nodes are plain objects and so indexable.
120
+ const result = /** @type {unknown } */ ( node [ field ] )
121
+ return result
122
+ }
123
+ }
0 commit comments