Skip to content

Instantly share code, notes, and snippets.

@silas
Last active December 11, 2020 22:31
Show Gist options
  • Select an option

  • Save silas/2593bc5d3af293d7f0360ae12a696e3d to your computer and use it in GitHub Desktop.

Select an option

Save silas/2593bc5d3af293d7f0360ae12a696e3d to your computer and use it in GitHub Desktop.

Revisions

  1. silas revised this gist Dec 11, 2020. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion toposort.js
    Original file line number Diff line number Diff line change
    @@ -20,7 +20,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    */

    // eslint-disable-next-line max-classes-per-file
    class CyclicalDependencyError extends Error {
    constructor(message, node) {
    super(message);
  2. silas revised this gist Dec 11, 2020. 1 changed file with 11 additions and 12 deletions.
    23 changes: 11 additions & 12 deletions toposort.js
    Original file line number Diff line number Diff line change
    @@ -18,8 +18,9 @@ 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.
    */
    */

    // eslint-disable-next-line max-classes-per-file
    class CyclicalDependencyError extends Error {
    constructor(message, node) {
    super(message);
    @@ -40,14 +41,11 @@ class Toposort {
    }

    sort() {
    let i = this.cursor;

    while (i--) {
    for (let i = this.cursor - 1; i >= 0; i--) {
    if (!this.visited[i]) {
    this.visit(this.nodes[i], i, new Set());
    }
    }

    return this.sorted;
    }

    @@ -61,18 +59,19 @@ class Toposort {

    let outgoing = this.outgoingEdges.get(node) || new Set();
    outgoing = Array.from(outgoing);
    outgoing.sort();

    i = outgoing.length;
    if (i) {
    if (outgoing.length) {
    predecessors.add(node);
    do {
    const child = outgoing[--i];
    this.visit(child, this.nodesHash.get(child), predecessors);
    } while (i);
    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.sorted[--this.cursor] = node;
    this.cursor -= 1;
    this.sorted[this.cursor] = node;
    }

    static makeOutgoingEdges(edges) {
  3. silas revised this gist Dec 11, 2020. 1 changed file with 25 additions and 56 deletions.
    81 changes: 25 additions & 56 deletions toposort.test.js
    Original file line number Diff line number Diff line change
    @@ -4,45 +4,16 @@ const { toposort, CyclicalDependencyError } = require('./toposort.js');

    describe('toposort', () => {
    it('should be sorted correctly', () => {
    const actual = toposort([
    ['3', '2'],
    ['2', '1'],
    ['6', '5'],
    ['5', '2'],
    ['5', '4'],
    ]);

    const solutions = [
    ['3', '6', '5', '2', '1', '4'],
    ['3', '6', '5', '2', '4', '1'],
    ['6', '3', '5', '2', '1', '4'],
    ['6', '5', '3', '2', '1', '4'],
    ['6', '5', '3', '2', '4', '1'],
    ['6', '5', '4', '3', '2', '1'],
    ];

    let matched = false;
    for (const solution of solutions) {
    let match = true;

    if (solution.length === actual.length) {
    for (let i = 0; i < solution.length; i++) {
    if (solution[i] !== actual[i]) {
    match = false;
    break;
    }
    }
    } else {
    match = false;
    }

    if (match) {
    matched = true;
    break;
    }
    }

    assert.isTrue(matched);
    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', () => {
    @@ -67,13 +38,14 @@ describe('toposort', () => {
    });

    it('should sort triangular dependency', () => {
    const actual = toposort([
    ['a', 'b'],
    ['a', 'c'],
    ['b', 'c'],
    ]);

    assert.deepEqual(actual, ['a', 'b', 'c']);
    assert.deepEqual(
    toposort([
    ['a', 'b'],
    ['a', 'c'],
    ['b', 'c'],
    ]),
    ['a', 'b', 'c']
    );
    });

    it('should sort giant graphs quickly', () => {
    @@ -93,15 +65,12 @@ describe('toposort', () => {
    const o1 = { k1: 'v1', nested: { k2: 'v2' } };
    const o2 = { k2: 'v2' };
    const o3 = { k3: 'v3' };
    const actual = toposort([
    [o1, o2],
    [o2, o3],
    ]);

    assert.deepEqual(actual, [
    { k1: 'v1', nested: { k2: 'v2' } },
    { k2: 'v2' },
    { k3: 'v3' },
    ]);
    assert.deepEqual(
    toposort([
    [o1, o2],
    [o2, o3],
    ]),
    [{ k1: 'v1', nested: { k2: 'v2' } }, { k2: 'v2' }, { k3: 'v3' }]
    );
    });
    });
  4. silas created this gist Dec 11, 2020.
    111 changes: 111 additions & 0 deletions toposort.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,111 @@
    /*
    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() {
    let i = this.cursor;

    while (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);

    i = outgoing.length;
    if (i) {
    predecessors.add(node);
    do {
    const child = outgoing[--i];
    this.visit(child, this.nodesHash.get(child), predecessors);
    } while (i);
    predecessors.delete(node);
    }

    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,
    };
    107 changes: 107 additions & 0 deletions toposort.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,107 @@
    const assert = require('chai').assert;

    const { toposort, CyclicalDependencyError } = require('./toposort.js');

    describe('toposort', () => {
    it('should be sorted correctly', () => {
    const actual = toposort([
    ['3', '2'],
    ['2', '1'],
    ['6', '5'],
    ['5', '2'],
    ['5', '4'],
    ]);

    const solutions = [
    ['3', '6', '5', '2', '1', '4'],
    ['3', '6', '5', '2', '4', '1'],
    ['6', '3', '5', '2', '1', '4'],
    ['6', '5', '3', '2', '1', '4'],
    ['6', '5', '3', '2', '4', '1'],
    ['6', '5', '4', '3', '2', '1'],
    ];

    let matched = false;
    for (const solution of solutions) {
    let match = true;

    if (solution.length === actual.length) {
    for (let i = 0; i < solution.length; i++) {
    if (solution[i] !== actual[i]) {
    match = false;
    break;
    }
    }
    } else {
    match = false;
    }

    if (match) {
    matched = true;
    break;
    }
    }

    assert.isTrue(matched);
    });

    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', () => {
    const actual = toposort([
    ['a', 'b'],
    ['a', 'c'],
    ['b', 'c'],
    ]);

    assert.deepEqual(actual, ['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' };
    const actual = toposort([
    [o1, o2],
    [o2, o3],
    ]);

    assert.deepEqual(actual, [
    { k1: 'v1', nested: { k2: 'v2' } },
    { k2: 'v2' },
    { k3: 'v3' },
    ]);
    });
    });