Skip to content

Commit 82fdc69

Browse files
committed
Refactor code-style
1 parent fe3b462 commit 82fdc69

File tree

3 files changed

+286
-162
lines changed

3 files changed

+286
-162
lines changed

lib/index.js

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
/**
22
* @typedef {import('unist').Node} Node
33
* @typedef {import('unist-util-visit').Test} Test
4-
*
4+
*/
5+
6+
/**
57
* @callback KeyFunction
68
* Function called with every added node (`Node`) to calculate the key to
79
* index on.
@@ -23,23 +25,19 @@ export class Index {
2325
* If `tree` is given, the index is initialized with all nodes, optionally
2426
* filtered by `test`.
2527
*
26-
* @param {string | KeyFunction} prop
28+
* @param {KeyFunction | string} prop
2729
* Field (`string`) to look up in each node to find keys or function called
2830
* with each node to calculate keys.
2931
* @param {Node | null | undefined} [tree]
30-
* Tree to index.
32+
* Tree to index (optional).
3133
* @param {Test | null | undefined} [test]
32-
* `is`-compatible test.
34+
* `is`-compatible test (optional).
3335
*/
3436
constructor(prop, tree, test) {
3537
/** @type {Map<unknown, Array<Node>>} */
3638
this.index = new Map()
3739
/** @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
4341

4442
if (tree) {
4543
visit(tree, test, (node) => {
@@ -108,3 +106,18 @@ export class Index {
108106
return this
109107
}
110108
}
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+
}

readme.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,20 @@ const tree = fromMarkdown(await fs.readFile('readme.md'))
7777
// Index on heading depth:
7878
const indexOnDepth = new Index('depth', tree, 'heading')
7979

80-
console.log(indexOnDepth.get(2).map((d) => toString(d)))
80+
console.log(
81+
indexOnDepth.get(2).map(function (d) {
82+
return toString(d)
83+
})
84+
)
8185

8286
// Index on definition identifier:
8387
const indexOnIdentifier = new Index('identifier', tree, 'definition')
8488

85-
console.log(indexOnIdentifier.get('unist').map((node) => node.url))
89+
console.log(
90+
indexOnIdentifier.get('unist').map(function (node) {
91+
return node.url
92+
})
93+
)
8694
```
8795

8896
Yields:

0 commit comments

Comments
 (0)