3 module.exports = visitParents
5 var convert = require('unist-util-is/convert')
11 visitParents.CONTINUE = CONTINUE
12 visitParents.SKIP = SKIP
13 visitParents.EXIT = EXIT
15 function visitParents(tree, test, visitor, reverse) {
18 if (typeof test === 'function' && typeof visitor !== 'function') {
28 // Visit a single node.
29 function one(node, index, parents) {
33 if (!test || is(node, index, parents[parents.length - 1] || null)) {
34 result = toResult(visitor(node, parents))
36 if (result[0] === EXIT) {
41 if (node.children && result[0] !== SKIP) {
42 subresult = toResult(all(node.children, parents.concat(node)))
43 return subresult[0] === EXIT ? subresult : result
49 // Visit children in `parent`.
50 function all(children, parents) {
52 var step = reverse ? -1 : 1
53 var index = (reverse ? children.length : min) + step
56 while (index > min && index < children.length) {
57 result = one(children[index], index, parents)
59 if (result[0] === EXIT) {
63 index = typeof result[1] === 'number' ? result[1] : index + step
68 function toResult(value) {
69 if (value !== null && typeof value === 'object' && 'length' in value) {
73 if (typeof value === 'number') {
74 return [CONTINUE, value]