Socket
Socket
Sign inDemoInstall

unist-util-reduce

Package Overview
Dependencies
2
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

unist-util-reduce

Parse unist trees, and map over nodes that pass a predicate function


Version published
Maintainers
1
Weekly downloads
668
increased by15.97%

Weekly downloads

Readme

Source

unist-util-reduce

Chat

unist utility to recursively reduce a tree

Install

npm:

npm install unist-util-reduce

Usage

const u = require("unist-builder");
const reduce = require("unist-util-reduce");
const assert = require("assert");

const tree = u("tree", [
  u("leaf", "1"),
  u("node", [u("leaf", "2")]),
  u("void"),
  u("leaf", "3")
]);

const newTree = reduce(tree, function(node) {
  if (node.value === "2") {
    const duplicateNode = { ...node, value: "two" };
    return [duplicateNode, node];
  }
  return node;
});

const expected = u("tree", [
  u("leaf", "1"),
  u("node", [u("leaf", "two"), u("leaf", "2")]),
  u("void"),
  u("leaf", "3")
]);

assert.deepEqual(newTree, expected);

NOTE: leaf with value 2 is visited before it's parent node. By the time your transform function is invoked, it's children will already have been passed through transform.

API

reduce(tree, transform)

  • tree - A node of type Parent
  • transform - A function with the signature:
    • (node: Node, path: number[], root: Paretn) => Node | Node[]
      • node - The Node in the tree to be transformed
      • path - The path to reach this node in each level of the tree
      • root - The Parent root node
      • Returns - What you return is passed to .concat() on the children array of the node's parent.

License

MIT © Callum Macdonald / GeneroUS Labs

FAQs

Last updated on 11 Jun 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc