"use strict"; const kahn = require("./kahn"); module.exports = function sortDependencies(items) { let dependencyMap = new Map(); let nodeMap = new Map(); // The below code 1) inverts child-specifying nodes to parent-specifying nodes, and 2) ensures that nodes reference in-memory objects rather than IDs, so they work with the implementation of Kahn's algorithm. TODO: This should probably be made nicer at some point... items.forEach((item) => { dependencyMap.set(item.id, item); nodeMap.set(item.id, { id: item.id, children: [] }); }); items.forEach((item) => { Object.values(item.deps) .filter((dep => dep !== item.id)) .forEach((dep) => { nodeMap.get(dep).children.push(nodeMap.get(item.id)); }); nodeMap.get(item.id).parents = Object.values(item.deps) .filter((id => id !== item.id)) .map((id) => nodeMap.get(id)); }); let sortedNodes = kahn(Array.from(nodeMap.values())); return sortedNodes.map((node) => { return dependencyMap.get(node.id); }); };