UNPKG

1.34 kBJavaScriptView Raw
1/**
2 * @author Richard Smith-Unna
3 * @copyright 2016 Richard Smith-Unnar
4 * @license MIT
5 * @module unist:find
6 * @fileoverview Unist node finder
7 *
8 * @typedef {import('unist').Node} Node
9 *
10 * @typedef {string} TestStr
11 * Finds first node with a truthy property matching string.
12 * @typedef {Object.<string, unknown>} TestObj
13 * Finds first node that has matching values for all properties of object.
14 * @typedef {<V extends Node>(node: V) => boolean} TestFn
15 * Finds first node for which function returns true when passed node as argument.
16 */
17
18var visit = require('unist-util-visit')
19var iteratee = require('lodash.iteratee')
20
21/**
22 * Unist node finder utility.
23 *
24 * @param tree
25 * Node to search.
26 * @param condition
27 * Condition used to test each node.
28 * @returns
29 * The first node that matches condition, or undefined if no node matches.
30 * @type {<V extends Node>(tree: Node, condition: TestStr | TestObj | TestFn) => V | undefined}
31 */
32module.exports = function find (tree, condition) {
33 if (!tree) throw new Error('unist-util-find requires a tree to search')
34 if (!condition) throw new Error('unist-util-find requires a condition')
35
36 const predicate = iteratee(condition)
37 let result
38
39 visit(tree, function (node) {
40 if (predicate(node)) {
41 result = node
42 return false
43 }
44 })
45
46 return result
47}