diff --git a/package.json b/package.json index f944aa8..8fc86ee 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@aureooms/js-topological-sorting", "description": "Topological sorting for JavaScript", - "version": "0.0.1", + "version": "0.1.0", "license": "AGPL-3.0", "author": "aureooms", "homepage": "https://aureooms.github.io/js-topological-sorting", diff --git a/src/index.js b/src/index.js index 15bcfe5..ff71f27 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,4 @@ +import kahn1962 from './kahn1962.js'; import sorted from './sorted.js'; -export {sorted}; +export {kahn1962, sorted}; diff --git a/src/kahn.js b/src/kahn1962.js similarity index 68% rename from src/kahn.js rename to src/kahn1962.js index ad2f507..978068e 100644 --- a/src/kahn.js +++ b/src/kahn1962.js @@ -3,11 +3,11 @@ * * See https://en.wikipedia.org/wiki/Topological_sorting#CITEREFKahn1962 * - * @param {any} queue - * @param {any} graph + * @param {any} queue - Free vertices. + * @param {any} graph - Edges of the graph. * @returns {Iterable} The vertices in topological order. */ -export default function* kahn(queue, graph) { +export default function* kahn1962(queue, graph) { while (true) { const u = queue.pop(); if (u === undefined) break; @@ -19,8 +19,4 @@ export default function* kahn(queue, graph) { } } } - - if (graph.size > 0) { - throw new Error('kahn: graph has at least one cycle'); - } } diff --git a/src/sorted.js b/src/sorted.js index 7e21e7c..202a7a9 100644 --- a/src/sorted.js +++ b/src/sorted.js @@ -1,16 +1,17 @@ import Heap from '@aureooms/js-pairing-heap'; import {EfficientlyInvertiblePairs as Pairs} from '@aureooms/js-pairs'; -import kahn from './kahn.js'; +import kahn1962 from './kahn1962.js'; /** * Sort the vertices topologically breaking ties according to a given function. * * @param {Iterable} edges - The input graph as a list of edges. - * @param {(a: any, b: any) => Number} breakTies - The function to break ties. + * @param {Function} breakTies - The function to break ties. * @returns {Iterable} The vertices sorted in topological order. + * @throws {Error} If the input graph contains a cycle. */ -export default function sorted(edges, breakTies = undefined) { +export default function* sorted(edges, breakTies = undefined) { const graph = Pairs.from(edges); const queue = breakTies ? new Heap(breakTies) : []; @@ -19,5 +20,11 @@ export default function sorted(edges, breakTies = undefined) { for (const [, v] of graph) freeVertices.delete(v); for (const u of freeVertices) queue.push(u); - return kahn(queue, graph); + yield* kahn1962(queue, graph); + + if (graph.size > 0) { + throw new Error( + '@aureooms/js-topological-sorting#sorted: input graph contains a cycle', + ); + } }