@unction/treeify
TypeScript icon, indicating that this package has built-in type declarations

13.16.0 • Public • Published

@unction/treeify

Tests Stability Dependencies

Array<FoldFunctionType<A, B>> => Array => TreeType

This takes a list of functions (the folders) and an array of objects or an object of objects (the collection) to create a tree. Each function in the list of folders will in some way return a new object. All of the objects produced are then turned into a final tree.

const collection = [
  {
    id: "a1",
    type: "resources",
    attributes: {
      version: "v1",
      namespace: "accounts",
    }
  },
  {
    id: "a2",
    type: "resources",
    attributes: {
      version: "v1",
      namespace: "accounts",
    }
  },
  {
    id: "b1",
    type: "resources",
    attributes: {
      version: "v1",
      namespace: "profiles",
    }
  },
  {
    id: "b1",
    type: "resources",
    attributes: {
      version: "v2",
      namespace: "profiles",
    }
  }
]

The order goes from outer layer to deeper layer, so in this case the outer level properties will be based on key("type"), and the deepest layer properties will be based on key("id").

const functions =

treeify(
  [
    groupBy(key("type")),
    groupBy(keyChain(["attributes", "namespace"])),
    groupBy(keyChain(["attributes", "version"])),
    indexBy(key("id")),
  ]
)(
  collection
)

The resulting object looks like this:

{
  resources: {
    accounts: {
      v1: {
        a1: {
          id: "a1",
          type: "resources",
          attributes: {
            version: "v1",
            namespace: "accounts",
          }
        },
        a2: {
          id: "a2",
          type: "resources",
          attributes: {
            version: "v1",
            namespace: "accounts",
          }
        }
      }
    },
    profiles: {
      v1: {
        b1: {
          id: "b1",
          type: "resources",
          attributes: {
            version: "v1",
            namespace: "profiles",
          }
        }
      },
      v2: {
        b1: {
          id: "b1",
          type: "resources",
          attributes: {
            version: "v2",
            namespace: "profiles",
          }
        }
      }
    }
  }
}

Readme

Keywords

Package Sidebar

Install

npm i @unction/treeify

Weekly Downloads

3

Version

13.16.0

License

SEE LICENSE IN LICENSE

Unpacked Size

22.9 kB

Total Files

7

Last publish

Collaborators

  • krainboltgreene