Skip to content

Commit

Permalink
Fix next after close
Browse files Browse the repository at this point in the history
  • Loading branch information
compulim committed Jun 8, 2024
1 parent 4c7d82a commit 9fa4ffa
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
10 changes: 10 additions & 0 deletions packages/iter-fest/src/PushAsyncIterableIterator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,13 @@ describe('comprehensive', () => {
test('should completed the for-loop', () => expect(done).toHaveBeenCalledTimes(1));
});
});

test('push after close should close the iterable', async () => {
const iterable = new PushAsyncIterableIterator();

iterable.close();
await expect(iterable.next()).resolves.toEqual({ done: true, value: undefined });

iterable.push(1);
await expect(iterable.next()).resolves.toEqual({ done: true, value: undefined });
});
8 changes: 6 additions & 2 deletions packages/iter-fest/src/PushAsyncIterableIterator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import withResolvers from './private/withResolvers';
const CLOSE = Symbol('close');

export class PushAsyncIterableIterator<T> implements AsyncIterableIterator<T> {
#closed: boolean = false;
#pushResolvers: PromiseWithResolvers<T | typeof CLOSE> = withResolvers();

[Symbol.asyncIterator]() {
return this;
}

close() {
this.#closed = true;
this.#pushResolvers.resolve(CLOSE);
}

Expand All @@ -24,7 +26,9 @@ export class PushAsyncIterableIterator<T> implements AsyncIterableIterator<T> {
}

push(value: T) {
this.#pushResolvers.resolve(value);
this.#pushResolvers = withResolvers();
if (!this.#closed) {
this.#pushResolvers.resolve(value);
this.#pushResolvers = withResolvers();
}
}
}

0 comments on commit 9fa4ffa

Please sign in to comment.