UNPKG

@exadel/esl

Version:

Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components

33 lines (32 loc) 1.18 kB
/** * Builds hierarchy based on level property from anchor data. * Anchors with smaller level values become parents of following anchors with larger values. * Uses `data.level` property from the anchor's data object (set via `esl-anchor="level: X"` attribute). * @param flatAnchors - flat list of anchors in DOM order * @returns hierarchical anchors list (roots only) */ export function buildHierarchyByLevel(flatAnchors) { var _a, _b; const roots = []; const stack = []; for (const anchor of flatAnchors) { anchor.children = []; anchor.parent = null; // Find parent in stack while (stack.length > 0 && ((_a = stack[stack.length - 1].data.level) !== null && _a !== void 0 ? _a : 0) >= ((_b = anchor.data.level) !== null && _b !== void 0 ? _b : 0)) { stack.pop(); } if (stack.length === 0) { // Root level roots.push(anchor); } else { // Child level const parent = stack[stack.length - 1]; parent.children.push(anchor); anchor.parent = parent.id; } stack.push(anchor); } return roots; }