unfold-with

3.0.5 • Public • Published

unfold-with

An unfold helper, inspired by this awesome article.

travis npm

Install:

npm i unfold-with

API

unfoldWidth((value) => [value, next-value] || null, initial-value)

  • (value) => [value, next-value]. Required. A function which takes a value and returns either an array of the form [value, next-value] or null || undefined.
  • initial-value. Optional. If present, the first call to the function above will be invoked with this value.

Examples

A simple range:

const unfold = require("unfold-with");

const rangePositive = (start, end) =>
  unfold((x) => (x <= end ? [x, x + 1] : null), start);
console.log(rangePositive(-2, 2)); // [ -2, -1, 0, 1, 2 ]

Or a tree:

const unfold = require("unfold-with");

// example taken from http://raganwald.com/2016/11/30/anamorphisms-in-javascript.html
const tree = {
  label: 1,
  children: [
    {
      label: 2,
      children: [
        {
          label: 4,
          children: [],
        },
        {
          label: 5,
          children: [],
        },
      ],
    },
    {
      label: 3,
      children: [
        {
          label: 6,
          children: [],
        },
      ],
    },
  ],
};

const depthFirst = (input) =>
  unfold(
    (forest) =>
      forest.length > 0
        ? [forest[0].label, forest[0].children.concat(forest.slice(1))]
        : null,
    input
  );

const breadthFirst = (input) =>
  unfold(
    (forest) =>
      forest.length > 0
        ? [forest[0].label, forest.slice(1).concat(forest[0].children)]
        : null,
    input
  );

console.log(
  depthFirst([tree]), // [ 1, 2, 4, 5, 3, 6 ]
  breadthFirst([tree]) // [ 1, 2, 3, 4, 5, 6 ]
);

A few more examples are here.

Readme

Keywords

Package Sidebar

Install

npm i unfold-with

Weekly Downloads

4

Version

3.0.5

License

ISC

Unpacked Size

3.23 kB

Total Files

3

Last publish

Collaborators

  • max.nachlinger