-
Notifications
You must be signed in to change notification settings - Fork 120
/
fp.js
90 lines (80 loc) · 2.03 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
export { createSelector } from "reselect";
export {
compose,
reduce,
find,
findIndex,
filter,
get,
eq,
map,
keyBy,
some,
uniq
} from "lodash/fp";
export { concat, isString, isNumber, cloneDeep } from "lodash";
import { isArray, isFunction } from "lodash";
import compose from "lodash/fp/compose";
import get from "lodash/fp/get";
export const not =
(fn) =>
(...args) =>
!fn(...args);
export const bool = compose(not, not);
export const or =
(...fns) =>
(...args) => {
let result;
return fns.find((fn) => (result = fn(...args))) ? result : false;
};
export const and =
(...fns) =>
(...args) => {
let result;
return !fns.find((fn, idx) =>
idx === 0 ? !(result = fn(...args)) : !fn(...args)
)
? result
: false;
};
// Currently redux state is not immutable causing issues with real selectors
// This is a temporary hack to allow same code style until that is fixed.
export const createSelectorEager =
(keyFns, resultFn) =>
(...args) =>
resultFn(...keyFns.map((fn) => fn(...args)));
// Given a hash of keys to functions, creates a selector that returns a map of function results
export const selectorMap = (fns) =>
createSelectorEager(
Object.keys(fns).map((key) => fns[key]),
(...args) =>
Object.keys(fns).reduce(
(res, key, idx) => ({ ...res, [key]: args[idx] }),
{}
)
);
export const substruct = (structure, obj) =>
Object.keys(structure).reduce(
(res, key) => ({ ...res, [structure[key] || key]: get(key, obj) }),
{}
);
export const apply = (fn, ...args) => fn(...args);
export const replace = (list, predicate, replacement) => {
const idx = list.findIndex(predicate);
if (idx === -1) {
return list;
}
const rep = isFunction(replacement)
? replacement(list[idx], list, idx)
: replacement;
const newList = [...list];
newList[idx] = rep;
return newList;
};
export const mapArray = (arr, key) =>
isArray(arr)
? arr.reduce((acc, v) => {
acc[v[key]] = v;
return acc;
}, {})
: {};