Giter VIP home page Giter VIP logo

unist-util-parents's Introduction

unist-util-parents

Build Coverage Downloads Size Sponsors Backers Chat

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

Contents

What is this?

This utility creates a proxy of the tree that acts like the original tree upon reading, but each proxied node has a reference to its parent node.

When should I use this?

This package can be very useful for problems where it is needed to figure out what a nodes ancestors are, because unist itself is a non-cyclical data structure, and thus does not provide that information. On the other hand, this info on ancestors can also be gathered when walking the tree with unist-util-visit-parents.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install unist-util-parents

In Deno with esm.sh:

import {parent} from 'https://esm.sh/unist-util-parents@3'

In browsers with esm.sh:

<script type="module">
  import {parent} from 'https://esm.sh/unist-util-parents@3?bundle'
</script>

Use

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

const 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')
    ])
  ])
])

const wrapped = parents(tree)

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

const chain = []
while (node) {
  chain.push(node.type)
  node = node.parent
}

console.log(chain.reverse())

Yields:

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

API

This package exports the identifier parents. There is no default export.

parents(tree)

Create a proxy of tree that acts like the original tree upon reading, but each proxied node has a reference to its parent node.

Notes

The returned proxy imposes two additional fields on all of its nodes:

  • parent — parent link (or undefined for the root)
  • node — link to the original node

These new fields are not enumerable and the original tree is not changed. This means you can use JSON.stringify on 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.

To write changes to the tree, use .node to access the original tree.

Parameters
  • tree (Node) — tree to proxy
Returns

Proxy of tree (Proxy).

Proxy

A proxy of a Node that adds two additional fields:

  • parent — parent link (or undefined for the root)
  • node — link to the original node

Types

This package is fully typed with TypeScript. It exports the additional type Proxy.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, unist-util-parents@^3, compatible with Node.js 16.

Related

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

unist-util-parents's People

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unist-util-parents's Issues

Node instance in multiple parentNode.children

Hi !
Me again suggesting something on a possible misunderstanding ! :)

Do unist trees can be fully used with "node instance" referenced in multiple branch of the tree ?
If so, one specific node can have multiple parents.
This is the subject of this suggestion.

Subject of the feature

.parent property in wrapped tree should return multiples parents if the same node instance is referenced in multiple parentNode.children.

Problem

.parent is not usable is this kind of tree as it return only the first one find.

Expected behaviour

return 'parents' as an array.

show code

  • an illustrating jest test here. I can translate it to a tape one if there is interest / value added.
import parents from 'unist-util-parents'

describe('unist-util-parents feature for node with 2 or more parents', () => {
    it('Return all parents of a node instance in multiple parentNode.children', () => {

        const predicateTree = { type : 'predicateTree', children:[]}
        const parent1 = { type: 'predicate', children:[], id:'http://p/1'}
        const parent2 = { type: 'predicate', children:[], id:'http://p/2'}

        const objectOneParent  = { type: 'object', id:'http://o/1', value:'I only have one parent'}
        const objectTwoParents = { type: 'object', id:'http://o/2', value:'I have 2 parents !'}

        //build the tree
        parent1.children.push(objectTwoParents)
        parent2.children.push(objectTwoParents, objectOneParent)
        predicateTree.children.push(parent1, parent2)

        // wrap it
        const treeWithParents = parents(predicateTree)
        
        // w = wrapped
        const [wparent1, wparent2] = treeWithParents.children

        expect(wparent1.children.length).toBe(1)

        // objectTwoParents is under his 2 parents
        expect(wparent1.children[0]).toStrictEqual(objectTwoParents)
        expect(wparent2.children[0]).toStrictEqual(objectTwoParents)

        // get the wrapped object wO2P = object with 2 parents
        const [wO2P] = wparent2.children

        // but the parent relationship only return one parent
        console.log(wO2P.parent)
        expect(Array.isArray(wO2P.parent)).toBe(true)
    })
})

Thanks and regards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.