Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/each.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { spawn } from "./spawn.ts";
import { constant } from "./constant.ts";
import { createContext } from "./context.ts";
import { useScope } from "./scope.ts";
import { spawn } from "./spawn.ts";
import type { Operation, Stream, Subscription } from "./types.ts";
import { withResolvers } from "./with-resolvers.ts";

Expand Down Expand Up @@ -28,9 +29,16 @@ import { withResolvers } from "./with-resolvers.ts";
* @param stream - the stream to iterate
* @returns an operation to iterate `stream`
*/
export function each<T>(stream: Stream<T, unknown>): Operation<Iterable<T>> {
export function each<T>(
enumerable: Stream<T, unknown> | Subscription<T, unknown>,
): Operation<Iterable<T>> {
return {
*[Symbol.iterator]() {
let stream = typeof (enumerable as Subscription<T, unknown>).next ===
"function"
? constant(enumerable as Subscription<T, unknown>)
: enumerable as Stream<T, unknown>;

let scope = yield* useScope();
if (!scope.hasOwn(EachStack)) {
scope.set(EachStack, []);
Expand Down
21 changes: 21 additions & 0 deletions test/each.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "./suite.ts";
import {
createQueue,
each,
type Operation,
resource,
Expand Down Expand Up @@ -54,6 +55,26 @@ describe("each", () => {
});
});

it("can iterate subscriptions", async () => {
await run(function* () {
let queue = createQueue<number, void>();

queue.add(1);
queue.add(2);
queue.add(3);
queue.close();

let items = [];

for (let num of yield* each(queue)) {
items.push(num);
yield* each.next();
}

expect(items).toEqual([1, 2, 3]);
});
});

it("handles context correctly if you break out of a loop", async () => {
await expect(run(function* () {
let seq = sequence("hello world");
Expand Down
Loading