123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- import { isTag, hasChildren } from "domhandler";
- export function filter(test, node, recurse = true, limit = Infinity) {
- if (!Array.isArray(node))
- node = [node];
- return find(test, node, recurse, limit);
- }
- export function find(test, nodes, recurse, limit) {
- const result = [];
- for (const elem of nodes) {
- if (test(elem)) {
- result.push(elem);
- if (--limit <= 0)
- break;
- }
- if (recurse && hasChildren(elem) && elem.children.length > 0) {
- const children = find(test, elem.children, recurse, limit);
- result.push(...children);
- limit -= children.length;
- if (limit <= 0)
- break;
- }
- }
- return result;
- }
- export function findOneChild(test, nodes) {
- return nodes.find(test);
- }
- export function findOne(test, nodes, recurse = true) {
- let elem = null;
- for (let i = 0; i < nodes.length && !elem; i++) {
- const checked = nodes[i];
- if (!isTag(checked)) {
- continue;
- }
- else if (test(checked)) {
- elem = checked;
- }
- else if (recurse && checked.children.length > 0) {
- elem = findOne(test, checked.children, true);
- }
- }
- return elem;
- }
- export function existsOne(test, nodes) {
- return nodes.some((checked) => isTag(checked) &&
- (test(checked) ||
- (checked.children.length > 0 &&
- existsOne(test, checked.children))));
- }
- export function findAll(test, nodes) {
- var _a;
- const result = [];
- const stack = nodes.filter(isTag);
- let elem;
- while ((elem = stack.shift())) {
- const children = (_a = elem.children) === null || _a === void 0 ? void 0 : _a.filter(isTag);
- if (children && children.length > 0) {
- stack.unshift(...children);
- }
- if (test(elem))
- result.push(elem);
- }
- return result;
- }
|