UNPKG

es-grid-template

Version:

es-grid-template

38 lines (37 loc) 1.2 kB
type WithChildren<T> = T & { children?: WithChildren<T>[]; }; /** * Builds a tree structure from an array of objects based on `idProp` and `parentIdProp`. * When A[parentIdProp] === B[idProp], object A will be moved to B's `children`. * If an object's `parentIdProp` does not match any other object's `idProp`, * it will be treated as a top-level node in the tree. * @example * const array = [ * { id: 'node-1', parent: 'root' }, * { id: 'node-2', parent: 'root' }, * { id: 'node-3', parent: 'node-2' }, * { id: 'node-4', parent: 'node-2' }, * { id: 'node-5', parent: 'node-4' }, * ] * const tree = buildTree('id', 'parent', array) * expect(tree).toEqual([ * { id: 'node-1', parent: 'root' }, * { * id: 'node-2', * parent: 'root', * children: [ * { id: 'node-3', parent: 'node-2' }, * { * id: 'node-4', * parent: 'node-2', * children: [{ id: 'node-5', parent: 'node-4' }], * }, * ], * }, * ]) */ export default function buildTree<ID extends string, PID extends string, T extends { [key in ID | PID]: string; }>(idProp: ID, parentIdProp: PID, items: T[]): WithChildren<T>[]; export {};