|
1 | | -/** |
2 | | - * @typedef {import('unist').Node} Node |
3 | | - * @typedef {import('unist').Parent} Parent |
4 | | - * |
5 | | - * @typedef {string} Type |
6 | | - * @typedef {Record<string, unknown>} Props |
7 | | - * @typedef {import('unist-util-is').TestFunctionAnything} TestFunctionAnything |
8 | | - */ |
9 | | - |
10 | | -import {convert} from 'unist-util-is' |
11 | | - |
12 | | -/** |
13 | | - * Find the first node in `parent` before another `node` or before an index, |
14 | | - * that passes `test`. |
15 | | -
|
16 | | - * @param parent |
17 | | - * Parent node. |
18 | | - * @param index |
19 | | - * Child of `parent`, or it’s index. |
20 | | - * @param [test] |
21 | | - * `unist-util-is`-compatible test. |
22 | | - * @returns |
23 | | - * |
24 | | - */ |
25 | | -export const findBefore = |
26 | | - /** |
27 | | - * @type {( |
28 | | - * (<T extends Node>(node: Parent, index: Node|number, test: T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>|Array<T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>>) => T|null) & |
29 | | - * ((node: Parent, index: Node|number, test?: null|undefined|Type|Props|TestFunctionAnything|Array<Type|Props|TestFunctionAnything>) => Node|null) |
30 | | - * )} |
31 | | - */ |
32 | | - ( |
33 | | - /** |
34 | | - * @param {Parent} parent |
35 | | - * @param {Node|number} index |
36 | | - * @param {null|undefined|Type|Props|TestFunctionAnything|Array<Type|Props|TestFunctionAnything>} [test] |
37 | | - * @returns {Node|null} |
38 | | - */ |
39 | | - function (parent, index, test) { |
40 | | - const is = convert(test) |
41 | | - |
42 | | - if (!parent || !parent.type || !parent.children) { |
43 | | - throw new Error('Expected parent node') |
44 | | - } |
45 | | - |
46 | | - if (typeof index === 'number') { |
47 | | - if (index < 0 || index === Number.POSITIVE_INFINITY) { |
48 | | - throw new Error('Expected positive finite number as index') |
49 | | - } |
50 | | - } else { |
51 | | - index = parent.children.indexOf(index) |
52 | | - |
53 | | - if (index < 0) { |
54 | | - throw new Error('Expected child node or index') |
55 | | - } |
56 | | - } |
57 | | - |
58 | | - // Performance. |
59 | | - if (index > parent.children.length) { |
60 | | - index = parent.children.length |
61 | | - } |
62 | | - |
63 | | - while (index--) { |
64 | | - if (is(parent.children[index], index, parent)) { |
65 | | - return parent.children[index] |
66 | | - } |
67 | | - } |
68 | | - |
69 | | - return null |
70 | | - } |
71 | | - ) |
| 1 | +export {findBefore} from './lib/index.js' |
0 commit comments