Skip to content

Commit

Permalink
fix(util): ensureSortedSet handles null iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
tabcat committed Dec 2, 2024
1 parent 95597cf commit 5926307
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,16 @@ export function* readArray<T>(
}
}

const sentinel = Symbol();

export function* ensureSortedSet<T>(
iterable: Iterable<T>,
comparator: (a: T, b: T) => number,
): Generator<T> {
let previous: T | null = null;
let previous: T | typeof sentinel = sentinel;

for (const element of iterable) {
if (previous != null && comparator(element, previous) <= 0) {
if (previous !== sentinel && comparator(previous, element) >= 0) {
throw new Error("iterable is not a sorted set.");
}

Expand All @@ -79,10 +81,10 @@ export async function* ensureSortedSetAsync<T>(
iterable: AsyncIterable<T> | Iterable<T>,
comparator: (a: T, b: T) => number,
): AsyncGenerator<T> {
let previous: T | null = null;
let previous: T | typeof sentinel = sentinel;

for await (const element of iterable) {
if (previous != null && comparator(element, previous) <= 0) {
if (previous !== sentinel && comparator(previous, element) >= 0) {
throw new Error("async-iterable is not a sorted set.");
}

Expand Down

0 comments on commit 5926307

Please sign in to comment.