unified

Project: syntax-tree/unist-util-parents

Package: unist-util-parents@2.0.0

  1. Dependencies: 0·Dependents: 19
  2. unist utility to add references to parents on nodes in a tree
  1. util 128
  2. utility 124
  3. unist 120
  4. ast 29
  5. unist-util 25
  6. node 23
  7. reference 9
  8. walk 8
  9. parent 2
  10. parents 2

unist-util-parents

Build Coverage Downloads Size Sponsors Backers Chat

unist utility to add references to parents on nodes in a tree.

Instead of modifying the original syntax tree, this module returns a wrapper that makes it easier to traverse that tree.

Algorithms that work on regular unist trees are (mostly) guaranteed to work on wrapped trees, and each wrapped node maintains a reference to the node from which it originated.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install unist-util-parents

Use

import {u} from 'unist-builder'
import {parents} from 'unist-util-parents'

var tree = u('root', [
  u('leaf', 'leaf 1'),
  u('node', [
    u('leaf', 'leaf 2'),
    u('void'),
    u('node', [
      u('leaf', 'leaf 3'),
      u('node', [u('leaf', 'leaf 4')]),
      u('void'),
      u('leaf', 'leaf 5')
    ])
  ])
])

var wrapped = parents(tree)

// Leaf 4
var node = wrapped.children[1].children[2].children[1].children[0]

var chain = []
while (node) {
  chain.unshift(node.type)
  node = node.parent
}

console.log(chain)

Yields:

['root', 'node', 'node', 'node', 'leaf']

API

This package exports the following identifiers: parents. There is no default export.

parents(tree)

Returns a wrapped tree with a proxy that imposes two additional properties on all of its nodes:

None of these properties are enumerable, and the original tree is not changed. This means you can JSON.stringify the wrapped tree and it’s the same.

wrapped.children returns array of wrapped child nodes, so that any recursive algorithm will work on a wrapped tree just as well.

Remember to access .node before you commit any changes to a node.

Parameters
Returns

Node — A wrapped node: shallow copy of the given node with non-enumerable references to node and parent, and if tree had children, they are wrapped as well.

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