-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples.ts
76 lines (55 loc) · 1.76 KB
/
examples.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { delay } from "bluebird";
import { reducer } from "./index";
import { reduce } from "./index";
import { reducerAsync } from "./index";
import { reduceAsync } from "./index";
const stringsConcater = reducer(function* (strings: string[]) {
for (const str of strings) {
const previousResult: string = (yield) || "";
yield previousResult + str;
}
});
console.log(
stringsConcater(["a", "b", "c"])
);
// "abc"
function* stringsConcaterGen(strings: string[], delimiter: string) {
for (const str of strings) {
const previousResult: string = (yield) || "";
const optionalDelimiter = previousResult === "" ? "" : delimiter;
yield previousResult + optionalDelimiter + str;
}
}
console.log(
reduce(stringsConcaterGen(["a", "b", "c"], ","))
);
// "a,b,c"
const sumDelaysAsync = reducerAsync(async function* (delayMilliseconds: number[], extraMs: number) {
for (const delayMs of delayMilliseconds) {
const totalDelayedMilliseconds: number = (yield) || 0;
await delay(delayMs);
yield totalDelayedMilliseconds + delayMs + extraMs;
}
});
(async function () {
console.log(
await sumDelaysAsync([500, 1500, 1000], 1)
);
// 3003
})();
async function addDelay(totalDelayedMilliseconds: number, delayMs: number): Promise<number> {
await delay(delayMs);
return totalDelayedMilliseconds + delayMs;
}
async function* delayPlusAsyncGen(delayMilliseconds: number[]) {
for (const delayMs of delayMilliseconds) {
const totalDelayedMilliseconds: number = (yield) || 0;
yield addDelay(totalDelayedMilliseconds, delayMs);
}
}
(async function () {
console.log(
await reduceAsync(delayPlusAsyncGen([500, 1500, 1000]))
);
// 3000
})();