README
unist-util-index
unist utility to create a mutable index mapping property values or computed keys back to nodes.
Install
This package is ESM only:
Node 12+ is needed to use it and it must be import
ed instead of require
d.
npm:
npm install unist-util-index
Use
import fs from 'fs'
import remark from 'remark'
import toString from 'mdast-util-to-string'
import {Index} from 'unist-util-index'
// Parse and read this repo’s readme:
var tree = remark.parse(fs.readFileSync('readme.md'))
// Index on heading depth:
var index = new Index('depth', tree, 'heading')
console.log(index.get(2).map(toString))
// Index on definition identifier:
index = new Index('identifier', tree, 'definition')
console.log(index.get('unist').map(node => node.url))
Yields:
[ 'Install', 'Use', 'API', 'Related', 'Contribute', 'License' ]
[ 'https://github.com/syntax-tree/unist' ]
API
This package exports the following identifiers: Index
.
There is no default export.
class Index(prop|keyFn[, tree[, test]])
Create an index data structure that maps keys (calculated by keyFn
function or
the values at prop
in each node) to a list of nodes.
If tree
is given, the index is initialized with all nodes, optionally filtered
by test
.
Parameters
prop
(string
) — Property to look up in each node to find keyskeyFn
(Function
) — Function called with each node to calculate keystree
(Node?
) — Tree to indextest
(Test
, optional) —is
-compatible test (such as a type)
Returns
Index
— an index instance.
function keyFn(node)
Function called with every added node to return the key to index on.
Index#get(key)
Get nodes by key
(*
).
Returns a list of zero or more nodes (Array.<Node>
).
Index#add(node)
Add node
to the index (if not already present).
Index#remove(node)
Remove node
from the index (if present).
Related
unist-util-is
— Utility to check if a node passes a testunist-util-visit
— Utility to recursively walk over nodesunist-util-map
— Create a new tree by mapping by the provided functionunist-util-flatmap
— Create a new tree by mapping and then flatteningunist-util-select
— Select nodes with CSS-like selectors
Contribute
See contributing.md
in syntax-tree/.github
for ways to get
started.
See support.md
for ways to get help.
This project has a Code of Conduct. By interacting with this repository, organisation, or community you agree to abide by its terms.
License
MIT © Eugene Sharygin