-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathasync_iterators.js
63 lines (55 loc) · 1.3 KB
/
async_iterators.js
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
// @ts-check
'use strict'
// Note: Each of these iterators executes synchronously, and will not "run in parallel"
// I am supporting filter, reduce, some, every, map
export async function filter (arr, iter) {
const result = []
let index = 0
for (const item of arr) {
if (await iter(item, index++, arr)) result.push(item)
}
return result
}
export async function some (arr, iter) {
let index = 0
for (const item of arr) {
if (await iter(item, index++, arr)) return true
}
return false
}
export async function every (arr, iter) {
let index = 0
for (const item of arr) {
if (!(await iter(item, index++, arr))) return false
}
return true
}
export async function map (arr, iter) {
const result = []
let index = 0
for (const item of arr) {
result.push(await iter(item, index++, arr))
}
return result
}
export async function reduce (arr, iter, defaultValue) {
if (arr.length === 0) {
if (typeof defaultValue !== 'undefined') {
return defaultValue
}
throw new Error('Array has no elements.')
}
const start = typeof defaultValue === 'undefined' ? 1 : 0
let data = start ? arr[0] : defaultValue
for (let i = start; i < arr.length; i++) {
data = await iter(data, arr[i])
}
return data
}
export default {
filter,
some,
every,
map,
reduce
}