Last active
December 11, 2020 22:31
-
-
Save silas/2593bc5d3af293d7f0360ae12a696e3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2012 by Marcel Klehr <[email protected]> | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
class CyclicalDependencyError extends Error { | |
constructor(message, node) { | |
super(message); | |
this.node = node; | |
} | |
} | |
class Toposort { | |
constructor(edges) { | |
this.nodes = Toposort.makeUniqueNodes(edges); | |
this.edges = edges; | |
this.cursor = this.nodes.length; | |
this.sorted = new Array(this.cursor); | |
this.visited = {}; | |
// Better data structures make algorithm much faster. | |
this.outgoingEdges = Toposort.makeOutgoingEdges(this.edges); | |
this.nodesHash = Toposort.makeNodesHash(this.nodes); | |
} | |
sort() { | |
for (let i = this.cursor - 1; i >= 0; i--) { | |
if (!this.visited[i]) { | |
this.visit(this.nodes[i], i, new Set()); | |
} | |
} | |
return this.sorted; | |
} | |
visit(node, i, predecessors) { | |
if (predecessors.has(node)) { | |
throw new CyclicalDependencyError('Cyclical dependency', node); | |
} | |
if (this.visited[i]) return; | |
this.visited[i] = true; | |
let outgoing = this.outgoingEdges.get(node) || new Set(); | |
outgoing = Array.from(outgoing); | |
outgoing.sort(); | |
if (outgoing.length) { | |
predecessors.add(node); | |
for (let j = outgoing.length - 1; j >= 0; j--) { | |
const child = outgoing[j]; | |
this.visit(child, this.nodesHash.get(outgoing[j]), predecessors); | |
} | |
predecessors.delete(node); | |
} | |
this.cursor -= 1; | |
this.sorted[this.cursor] = node; | |
} | |
static makeOutgoingEdges(edges) { | |
const outgoingEdges = new Map(); | |
for (const edge of edges) { | |
if (!outgoingEdges.has(edge[0])) outgoingEdges.set(edge[0], new Set()); | |
if (!outgoingEdges.has(edge[1])) outgoingEdges.set(edge[1], new Set()); | |
outgoingEdges.get(edge[0]).add(edge[1]); | |
} | |
return outgoingEdges; | |
} | |
static makeNodesHash(nodes) { | |
const nodesHash = new Map(); | |
for (let i = 0, length = nodes.length; i < length; i++) { | |
nodesHash.set(nodes[i], i); | |
} | |
return nodesHash; | |
} | |
static makeUniqueNodes(edges) { | |
const uniqueNodes = new Set(); | |
for (const edge of edges) { | |
uniqueNodes.add(edge[0]); | |
uniqueNodes.add(edge[1]); | |
} | |
return Array.from(uniqueNodes); | |
} | |
} | |
const toposort = (edges) => new Toposort(edges).sort(); | |
module.exports = { | |
toposort, | |
CyclicalDependencyError, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('chai').assert; | |
const { toposort, CyclicalDependencyError } = require('./toposort.js'); | |
describe('toposort', () => { | |
it('should be sorted correctly', () => { | |
assert.deepEqual( | |
toposort([ | |
['3', '2'], | |
['2', '1'], | |
['6', '5'], | |
['5', '2'], | |
['5', '4'], | |
]), | |
['3', '6', '5', '2', '1', '4'] | |
); | |
}); | |
it('error on simple cyclic graphs', () => { | |
assert.throws(() => { | |
toposort([ | |
['foo', 'bar'], | |
['bar', 'foo'], // cyclic dependency | |
]); | |
}, CyclicalDependencyError); | |
}); | |
it('error on complex cyclic graphs', () => { | |
assert.throws(() => { | |
toposort([ | |
['foo', 'bar'], | |
['bar', 'ron'], | |
['john', 'bar'], | |
['tom', 'john'], | |
['ron', 'tom'], // cyclic dependency | |
]); | |
}, CyclicalDependencyError); | |
}); | |
it('should sort triangular dependency', () => { | |
assert.deepEqual( | |
toposort([ | |
['a', 'b'], | |
['a', 'c'], | |
['b', 'c'], | |
]), | |
['a', 'b', 'c'] | |
); | |
}); | |
it('should sort giant graphs quickly', () => { | |
const graph = []; | |
for (let i = 0; i < 100000; i++) { | |
graph.push([i, i + 1]); | |
} | |
const start = Date.now(); | |
toposort(graph); | |
const end = Date.now(); | |
assert.isBelow(end - start, 1000); | |
}); | |
it('should handle objects', () => { | |
const o1 = { k1: 'v1', nested: { k2: 'v2' } }; | |
const o2 = { k2: 'v2' }; | |
const o3 = { k3: 'v3' }; | |
assert.deepEqual( | |
toposort([ | |
[o1, o2], | |
[o2, o3], | |
]), | |
[{ k1: 'v1', nested: { k2: 'v2' } }, { k2: 'v2' }, { k3: 'v3' }] | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment