-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
76 lines (66 loc) · 1.55 KB
/
main.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
function range (n) {
return Array.apply(null, Array(n)).map((_, i) => i)
}
function inc (x) { return x + 1 }
function isEven (x) { return x % 2 === 0 }
function mapReduce (transformation) {
return (result, input) => {
return result.concat([transformation(input)])
}
}
function filterReduce (predicate) {
return (result, input) => {
return predicate(input)
? result.concat([input])
: result
}
}
function concat (result, input) {
return result.concat([input])
}
function mapping (transformation) {
return (reducer) => {
return (result, input) => {
// console.log('Inside maping', result, input)
return reducer(result, transformation(input))
}
}
}
function filtering (predicate) {
return (reducer) => {
return (result, input) => {
// console.log('run filtering', result, input)
return predicate(input)
? reducer(result, input)
: result
}
}
}
function compose () {
const fns = arguments
return (result) => {
for (var i = fns.length - 1; i > -1; i--) {
// console.log('Inside compose, result', result)
result = fns[i].call(this, result)
}
return result
}
}
const myLogic = compose(
filtering(isEven)
, filtering((input) => input < 10)
, mapping((x) => x * x)
, mapping(inc)
)
console.log([2, 3, 4].reduce(myLogic((x, y) => { return x + y }), 0))
module.exports = {
range: range,
inc: inc,
isEven: isEven,
mapReduce: mapReduce,
filterReduce: filterReduce,
concat: concat,
mapping: mapping,
filtering: filtering,
compose: compose
}