-
Notifications
You must be signed in to change notification settings - Fork 25
/
fp.js
48 lines (41 loc) · 1.1 KB
/
fp.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
const { push } = Array.prototype
// Disabling no-shadow so we can sanely curry
/* eslint-disable no-shadow */
export function map(fn, stores) {
return stores
? stores.map(store => fn(store.state))
: stores => map(fn, stores)
}
export function filter(fn, stores) {
return stores
? stores.filter(store => fn(store.state))
: stores => filter(fn, stores)
}
export function reduce(fn, stores, acc = {}) {
return stores
? stores.reduce((acc, store) => fn(acc, store.state), acc)
: stores => reduce(fn, stores)
}
export function flatMap(fn, stores) {
if (!stores) return (stores) => flatMap(fn, stores)
return stores.reduce((result, store) => {
const value = fn(store.state)
if (Array.isArray(value)) {
push.apply(result, value)
} else {
result.push(value)
}
return result
}, [])
}
export function zipWith(fn, a, b) {
if (!a && !b) {
return (a, b) => zipWith(fn, a, b)
}
const length = Math.min(a.length, b.length)
const result = Array(length)
for (let i = 0; i < length; i += 1) {
result[i] = fn(a[i].state, b[i].state)
}
return result
}