unist-utils-core
Version:
A collection of commonly used (albeit enhanced) algorithms based on unist and unist-util-xxx
60 lines • 2.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.findAncestor = exports.findAll = exports.find = void 0;
const test_1 = require("./test");
const visit_1 = require("./visit");
/**
* Return the first node that matches test, or undefined if no node matches.
*
* @param {Node} tree - Node(s) to search
* @param [tst] - 'is-compatible' test (such as a type).
*/
function find(tree, tst) {
let is = (0, test_1.test)(tst);
let result = undefined;
(0, visit_1.visit)(tree, is, function (node) {
result = node;
return visit_1.EXIT;
});
return result;
}
exports.find = find;
/**
* Return all nodes that match test, or an empty array if no node matches.
*
* @param {Node} tree - Node(s) to search
* @param [tst] - 'is-compatible' test (such as a type).
* @returns an Array of zero or more Nodes in the tree that matched the condition.
*/
function findAll(tree, tst) {
let is = (0, test_1.test)(tst);
let results = [];
(0, visit_1.visit)(tree, is, function (node) {
results.push(node);
return visit_1.CONTINUE;
});
return results;
}
exports.findAll = findAll;
/**
* Search upward (using the Node.parent property) for an ancestor that meets a supplied test.
*
* @param node The node from which to start the upward search.
* @param [tst] - 'is-compatible' test to apply to each parent along the upward walk.
* @returns An array representing the "path" to the first ancestor that matched the condition.
* The first element in the "path" array will be the ancestor that matched the condition, and the node's immediate parent will be the last element of the array.
* If no ancestors were found (or none passed the test), an empty array will be returned.
*/
function findAncestor(node, tst) {
let is = (0, test_1.test)(tst);
let results = [];
while (node && node.parent) {
results.unshift(node.parent);
if (is(node.parent))
return results;
node = node.parent;
}
return [];
}
exports.findAncestor = findAncestor;
//# sourceMappingURL=find.js.map