2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-05-18 13:39:12 +00:00
|
|
|
import { tee } from "./tee.ts";
|
2024-04-29 02:57:30 +00:00
|
|
|
import { assertEquals } from "@std/assert";
|
2021-05-18 13:39:12 +00:00
|
|
|
|
|
|
|
/** An example async generator */
|
|
|
|
const gen = async function* iter() {
|
|
|
|
yield 1;
|
|
|
|
yield 2;
|
|
|
|
yield 3;
|
|
|
|
};
|
|
|
|
|
2023-12-18 22:29:13 +00:00
|
|
|
Deno.test("tee() handles 2 branches", async () => {
|
2021-05-18 13:39:12 +00:00
|
|
|
const iter = gen();
|
2023-11-10 19:00:28 +00:00
|
|
|
const [res0, res1] = tee(iter).map(async (src) => await Array.fromAsync(src));
|
2021-05-18 13:39:12 +00:00
|
|
|
assertEquals(
|
|
|
|
await Promise.all([res0, res1]),
|
|
|
|
[
|
|
|
|
[1, 2, 3],
|
|
|
|
[1, 2, 3],
|
|
|
|
],
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2023-12-18 22:29:13 +00:00
|
|
|
Deno.test("tee() handles 3 branches with immediate consumption", async () => {
|
2021-05-18 13:39:12 +00:00
|
|
|
const iter = gen();
|
2023-11-10 19:00:28 +00:00
|
|
|
const [res0, res1, res2] = tee(iter, 3).map(async (src) =>
|
|
|
|
await Array.fromAsync(src)
|
|
|
|
);
|
2021-05-18 13:39:12 +00:00
|
|
|
assertEquals(
|
|
|
|
await Promise.all([res0, res1, res2]),
|
|
|
|
[
|
|
|
|
[1, 2, 3],
|
|
|
|
[1, 2, 3],
|
|
|
|
[1, 2, 3],
|
|
|
|
],
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2023-12-18 22:29:13 +00:00
|
|
|
Deno.test("tee() handles 3 branches with delayed consumption", async () => {
|
2021-05-18 13:39:12 +00:00
|
|
|
const iter = gen();
|
|
|
|
const iters = tee(iter, 3);
|
|
|
|
|
|
|
|
await new Promise<void>((resolve) => {
|
|
|
|
setTimeout(() => resolve(), 20);
|
|
|
|
});
|
|
|
|
|
|
|
|
assertEquals(
|
2023-11-10 19:00:28 +00:00
|
|
|
await Promise.all(iters.map(async (src) => await Array.fromAsync(src))),
|
2021-05-18 13:39:12 +00:00
|
|
|
[
|
|
|
|
[1, 2, 3],
|
|
|
|
[1, 2, 3],
|
|
|
|
[1, 2, 3],
|
|
|
|
],
|
|
|
|
);
|
|
|
|
});
|
2021-10-20 05:18:58 +00:00
|
|
|
|
2023-12-18 22:29:13 +00:00
|
|
|
Deno.test("tee() handles concurrent next() calls", async () => {
|
2021-10-20 05:18:58 +00:00
|
|
|
const [left] = tee(gen());
|
|
|
|
const l = left[Symbol.asyncIterator]();
|
|
|
|
assertEquals(await Promise.all([l.next(), l.next(), l.next(), l.next()]), [{
|
|
|
|
value: 1,
|
|
|
|
done: false,
|
|
|
|
}, {
|
|
|
|
value: 2,
|
|
|
|
done: false,
|
|
|
|
}, {
|
|
|
|
value: 3,
|
|
|
|
done: false,
|
|
|
|
}, {
|
|
|
|
value: undefined,
|
|
|
|
done: true,
|
|
|
|
}]);
|
|
|
|
});
|