UNPKG

@loken/hierarchies

Version:

Library for working with hierarchies of identifiers and identifiable objects.

60 lines (59 loc) 2.3 kB
import { Nodes } from "../nodes/nodes.js"; import { ChildMap } from "../utilities/child-map.js"; import { Hierarchy } from "./hierarchy.js"; class Hierarchies { /** Create a hierarchy of `Id`s. */ static createForIds() { return new Hierarchy((id) => id); } /** Create a hierarchy of `Item`s using the provided identify function. */ static createForItems(identify) { return new Hierarchy(identify); } /** * Create a hierarchy of `Id`s matching the `spec`. * * @param spec Specification of how to create an `Id` hierarchy from a list of relations, a multi-map of `Id`s or a hierarchy. */ static createWithIds(spec) { const childMap = ChildMap.fromIds(spec), roots = Nodes.assembleIds(childMap); return Hierarchies.createForIds().attachRoot(roots); } /** * Create a hierarchy of `Id`s matching the properties of the `source`. * * @param source The object describing the relations. * @param include Optional predicate used for determining whether a property should be included as an ID. */ static createWithPropertyIds(source, include) { const roots = Nodes.assemblePropertyIds(source, include); return Hierarchies.createForIds().attachRoot(roots); } /** * Create a hierarchy of `Item`s matching details from the `options`. * * @template Item The type of item. * @template Id The type of IDs. * @param items The items to wrap in nodes. * @param identify Means of getting an ID for an item. * @param options Options with details on how to create an `Item` hierarchy from a list of relations, a multi-map of `Id`s, * a hierarchy or functions for inferring the relations from each item. * @returns The fully linked `Hierarchy<Item, Id>`. */ static createWithItems(options) { let roots; if (options.children) roots = Nodes.assembleItemsWithChildren(options.items, options.children); else if (options.parent) roots = Nodes.assembleItemsWithParents(options.items, options.parent); else { const childMap = ChildMap.fromItems(options); roots = Nodes.assembleItems(options.items, options.identify, childMap); } return new Hierarchy(options.identify).attachRoot(roots); } } export { Hierarchies }; //# sourceMappingURL=hierarchies.js.map