Skip to content
Merged
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
20 changes: 9 additions & 11 deletions lib/lift.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { shift } from "./deps.ts";
import { type Operation } from "./types.ts";

/**
Expand All @@ -16,20 +17,17 @@ import { type Operation } from "./types.ts";
* @returns a function returning an operation that invokes `fn` when evaluated
*/
export function lift<TArgs extends unknown[], TReturn>(
fn: Fn<TArgs, TReturn>,
): LiftedFn<TArgs, TReturn> {
fn: (...args: TArgs) => TReturn,
): (...args: TArgs) => Operation<TReturn> {
return (...args: TArgs) => {
return ({
[Symbol.iterator]() {
let value = fn(...args);
return { next: () => ({ done: true, value }) };
*[Symbol.iterator]() {
return yield () => {
return shift(function* (k) {
k.tail({ ok: true, value: fn(...args) });
});
};
},
});
};
}

type Fn<TArgs extends unknown[], TReturn> = (...args: TArgs) => TReturn;

type LiftedFn<TArgs extends unknown[], TReturn> = (
...args: TArgs
) => Operation<TReturn>;
23 changes: 23 additions & 0 deletions test/lift.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { createSignal, each, lift, run, sleep, spawn } from "../mod.ts";
import { describe, expect, it } from "./suite.ts";

describe("lift", () => {
it("safely does not continue if the call stops the operation", async () => {
let reached = false;

await run(function* () {
let signal = createSignal<void, void>();

yield* spawn(function* () {
yield* sleep(0);
yield* lift(signal.close)();

reached = true;
});

for (let _ of yield* each(signal));
});

expect(reached).toBe(false);
});
});