Skip to content

Commit

Permalink
wrap
Browse files Browse the repository at this point in the history
  • Loading branch information
neurosnap committed Nov 22, 2023
1 parent 7e73d52 commit bab7be0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
16 changes: 12 additions & 4 deletions lib/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ function isPromise(p: unknown): boolean {
if (!p) return false;
return isFunc((p as PromiseLike<unknown>).then);
}
// iterator must implement both `.next` and `.throw`
// built-in iterators are not considered iterators to `call()`
function isIterator(it: unknown): boolean {
if (!it) return false;
return isFunc((it as Iterator<unknown>).next) &&
Expand Down Expand Up @@ -68,12 +70,18 @@ export function call<T>(callable: Callable<T>): Operation<T | Iterable<T>> {
return action(function* (resolve, reject) {
try {
let op = typeof callable === "function" ? callable() : callable;
if (isIterable(op)) {
resolve(yield* op as Operation<T>);
if (isPromise(op)) {
resolve(yield* expect(op as Promise<T>));
} else if (isIterator(op)) {
resolve(yield* op as Operation<T>);
} else if (isPromise(op)) {
resolve(yield* expect(op as Promise<T>));
} else if (isIterable(op)) {
let iterable = op as Iterable<unknown>;
let iter = iterable[Symbol.iterator]();
if (isIterator(iter)) {
resolve(yield* op as Operation<T>);
} else {
resolve(op as T);
}
} else {
resolve(op as T);
}
Expand Down
19 changes: 18 additions & 1 deletion test/call.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,24 @@ describe("call", () => {
await expect(run(() => call(() => 42))).resolves.toEqual(42);
});

it.only("evaluates a vanilla function that returns an iterable", async () => {
it("evaluates a vanilla function that returns an iterable string", async () => {
await expect(run(() => call(() => "123"))).resolves.toEqual("123");
});

it("evaluates a vanilla function that returns an iterable array", async () => {
await expect(run(() => call(() => [1, 2, 3]))).resolves.toEqual([1, 2, 3]);
});

it("evaluates a vanilla function that returns an iterable map", async () => {
let map = new Map();
map.set("1", 1);
map.set("2", 2);
map.set("3", 3);
await expect(run(() => call(() => map))).resolves.toEqual(map);
});

it("evaluates a vanilla function that returns an iterable set", async () => {
let arr = new Set([1, 2, 3]);
await expect(run(() => call(() => arr))).resolves.toEqual(arr);
});
});

0 comments on commit bab7be0

Please sign in to comment.