Skip to content

Commit ab91e6f

Browse files
🩹 fix(api): Correctly handle undefined breakTies.
1 parent 5a14bc4 commit ab91e6f

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ sorted(["ab", "bc"]); // abc
1414

1515
// Add a comparison function to break ties.
1616
import {increasing} from '@aureooms/js-compare';
17-
sorted(["ab", "cd"], increasing); // acbd
17+
sorted(["ab", "cd"], increasing); // abcd
18+
19+
import {decreasing} from '@aureooms/js-compare';
20+
sorted(["ab", "cd"], decreasing); // cdab
1821
```
1922

2023
[![License](https://img.shields.io/github/license/aureooms/js-topological-sorting.svg)](https://raw.githubusercontent.com/aureooms/js-topological-sorting/main/LICENSE)

src/sorted.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ import kahn from './kahn.js';
1010
* @param {(a: any, b: any) => Number} breakTies - The function to break ties.
1111
* @returns {Iterable<any>} The vertices sorted in topological order.
1212
*/
13-
export default function sorted(edges, breakTies = (_a, _b) => -1) {
13+
export default function sorted(edges, breakTies = undefined) {
1414
const graph = Pairs.from(edges);
1515

16-
const queue = new Heap(breakTies);
16+
const queue = breakTies ? new Heap(breakTies) : [];
1717
const freeVertices = new Set();
1818
for (const [u] of graph) freeVertices.add(u);
1919
for (const [, v] of graph) freeVertices.delete(v);

test/src/api.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,21 @@ test('Triangle after edge', (t) => {
124124
const edges = ['xa', 'ab', 'bc', 'ca'];
125125
t.throws(() => [...sorted(edges)], {message: /cycle/});
126126
});
127+
128+
test('README example #1', (t) => {
129+
const edges = ['ab', 'bc'];
130+
const expected = ['a', 'b', 'c'];
131+
t.deepEqual([...sorted(edges)], expected);
132+
});
133+
134+
test('README example #2', (t) => {
135+
const edges = ['ab', 'cd'];
136+
const expected = ['a', 'b', 'c', 'd'];
137+
t.deepEqual([...sorted(edges, increasing)], expected);
138+
});
139+
140+
test('README example #3', (t) => {
141+
const edges = ['ab', 'cd'];
142+
const expected = ['c', 'd', 'a', 'b'];
143+
t.deepEqual([...sorted(edges, decreasing)], expected);
144+
});

0 commit comments

Comments
 (0)