Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Express each() as a function #825

Merged
merged 1 commit into from
Nov 9, 2023
Merged
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
36 changes: 11 additions & 25 deletions lib/each.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,29 +25,7 @@ import { createContext } from "./context.ts";
* @param stream - the stream to iterate
* @returns an operation to iterate `stream`
*/
export const each = iterate as Each;

/**
* @ignore
*/
export type Each = typeof iterate & {
/**
* Indicate that the current iteration in a for-each loop is complete.
*
* @see {@link each}
*/
next: Operation<void>;
};

interface EachLoop<T> {
subscription: Subscription<T, unknown>;
current: IteratorResult<T>;
stale?: true;
}

const EachStack = createContext<EachLoop<unknown>[]>("each");

function iterate<T>(stream: Stream<T, unknown>): Operation<Iterable<T>> {
export function each<T>(stream: Stream<T, unknown>): Operation<Iterable<T>> {
return {
*[Symbol.iterator]() {
let subscription = yield* stream.subscribe();
Expand All @@ -65,7 +43,7 @@ function iterate<T>(stream: Stream<T, unknown>): Operation<Iterable<T>> {
next() {
if (context.stale) {
let error = new Error(
`for each loop did not use each.next operation before continuing`,
`for each loop did not use each.next() operation before continuing`,
);
error.name = "IterationError";
throw error;
Expand All @@ -87,7 +65,7 @@ function iterate<T>(stream: Stream<T, unknown>): Operation<Iterable<T>> {
};
}

iterate.next = function next() {
each.next = function next() {
return {
name: "each.next()",
*[Symbol.iterator]() {
Expand All @@ -107,3 +85,11 @@ iterate.next = function next() {
},
} as Operation<void>;
};

interface EachLoop<T> {
subscription: Subscription<T, unknown>;
current: IteratorResult<T>;
stale?: true;
}

const EachStack = createContext<EachLoop<unknown>[]>("each");