-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
54 lines (42 loc) · 1.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
const is = require('unist-util-is');
const find = require('unist-util-find');
function findAllBetween(parent, start, end, test) {
if (!parent || !parent.type || !parent.children) {
throw new Error('Expected parent node');
}
const {children} = parent;
const results = [];
let index = check(start);
const length = check(end);
let child;
while (++index < length) {
child = children[index];
if (is(child, test, index, parent)) {
results.push(child);
}
}
return results;
function check(index) {
if (index && index.type) {
// `find` will match the parent node but we only want
// to check child nodes.
if (parent.type === index.type) {
parent = {
type: parent.type + '-root',
children: parent.children
};
}
const node = find(parent, index);
index = children.indexOf(node);
}
if (isNaN(index) || index < 0 || index === Infinity) {
throw new Error('Expected positive finite index or child node');
}
if (index >= children.length) {
index = children.length - 1;
}
return index;
}
}
module.exports = findAllBetween;