|
| 1 | +import { delay } from "./delay.ts"; |
| 2 | +import type { Result } from "./types.ts"; |
| 3 | +import { sort, sortSettled } from "./sort.ts"; |
| 4 | +import { assertEquals } from "./deps_test.ts"; |
| 5 | + |
| 6 | +Deno.test("sort()", async (t) => { |
| 7 | + await t.step("return in order of settled", async () => { |
| 8 | + const results: number[] = []; |
| 9 | + |
| 10 | + for await ( |
| 11 | + const waited of sort( |
| 12 | + [1000, 2000, 500, 1500].map((n, index) => delay(n).then(() => index)), |
| 13 | + ) |
| 14 | + ) { |
| 15 | + results.push(waited); |
| 16 | + } |
| 17 | + |
| 18 | + assertEquals(results, [2, 0, 3, 1]); |
| 19 | + }); |
| 20 | + |
| 21 | + await t.step("ignore errors", async () => { |
| 22 | + const results: number[] = []; |
| 23 | + |
| 24 | + for await ( |
| 25 | + const waited of sort( |
| 26 | + [1000, 2000, 1500, 500].map(async (n, index) => { |
| 27 | + if (index < 2) throw Error(`Error: ${index}`); |
| 28 | + await delay(n); |
| 29 | + return index; |
| 30 | + }), |
| 31 | + ) |
| 32 | + ) { |
| 33 | + results.push(waited); |
| 34 | + } |
| 35 | + |
| 36 | + assertEquals(results, [3, 2]); |
| 37 | + }); |
| 38 | +}); |
| 39 | + |
| 40 | +Deno.test("sortSettled()", async (t) => { |
| 41 | + await t.step("return in order of settled", async () => { |
| 42 | + const results: Result<number>[] = []; |
| 43 | + |
| 44 | + for await ( |
| 45 | + const waited of sortSettled( |
| 46 | + [1000, 2000, 500, 1500].map((n, index) => delay(n).then(() => index)), |
| 47 | + ) |
| 48 | + ) { |
| 49 | + results.push(waited); |
| 50 | + } |
| 51 | + |
| 52 | + assertEquals(results, [ |
| 53 | + { success: true, value: 2 }, |
| 54 | + { success: true, value: 0 }, |
| 55 | + { success: true, value: 3 }, |
| 56 | + { success: true, value: 1 }, |
| 57 | + ]); |
| 58 | + }); |
| 59 | + |
| 60 | + await t.step("catch errors", async () => { |
| 61 | + const results: Result<number>[] = []; |
| 62 | + |
| 63 | + for await ( |
| 64 | + const waited of sortSettled( |
| 65 | + [1000, 2000, 1500, 500].map(async (n, index) => { |
| 66 | + if (index < 2) throw `Error: ${index}`; |
| 67 | + await delay(n); |
| 68 | + return index; |
| 69 | + }), |
| 70 | + ) |
| 71 | + ) { |
| 72 | + results.push(waited); |
| 73 | + } |
| 74 | + |
| 75 | + assertEquals(results, [ |
| 76 | + { success: false, reason: "Error: 0" }, |
| 77 | + { success: false, reason: "Error: 1" }, |
| 78 | + { success: true, value: 3 }, |
| 79 | + { success: true, value: 2 }, |
| 80 | + ]); |
| 81 | + }); |
| 82 | +}); |
0 commit comments