UNPKG

@rafa93br/toposort

Version:

40 lines (33 loc) 1.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hasIncomingEdges = function hasIncomingEdges(node) { return node.edges.length; }; var noIncomingEdges = function noIncomingEdges(node) { return !node.edges.length; }; var removeEdge = function removeEdge(adjacentVertex, node) { node.edges = node.edges.filter(function (vertex) { return vertex !== adjacentVertex; }); return node; }; exports.default = function () { var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var noEdges = nodes.filter(noIncomingEdges); var withEdges = nodes.filter(hasIncomingEdges); var sorted = []; while (noEdges.length) { var node = noEdges.pop(); sorted.push(node); withEdges = withEdges.map(removeEdge.bind(null, node.name)); var newNoEdges = withEdges.filter(noIncomingEdges); noEdges = noEdges.concat(newNoEdges); withEdges = withEdges.filter(hasIncomingEdges); } return sorted.map(function (node) { return node.name; }); };