-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcore.js
128 lines (109 loc) · 2.84 KB
/
core.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Core FRP functions
const FRP = {}
FRP.map = function(valueTransform) {
return function(eventStream) {
return function(next) {
eventStream(function(value) {
next(valueTransform(value))
})
}
}
}
FRP.bind = function(valueToEvent) {
return function(eventStream) {
return function(next) {
eventStream(function(value) {
valueToEvent(value)(next)
})
}
}
}
FRP.filter = function(predicate) {
return function(eventStream) {
return function(next) {
eventStream(function(value) {
if (predicate(value)) next(value)
})
}
}
}
FRP.reject = function(predicate) {
return function(eventStream) {
return function(next) {
eventStream(function(value) {
if (!predicate(value)) next(value)
})
}
}
}
FRP.fold = function(step, initial) {
return function(eventStream) {
return function(next) {
let accumulated = initial
eventStream(function (value) {
next(accumulated = step(accumulated, value))
})
}
}
}
FRP.merge = function(eventStreamA) {
return function(eventStreamB) {
return function(next) {
eventStreamA(value => next(value))
eventStreamB(value => next(value))
}
}
}
FRP.compose = function(eventStream, ...operations) {
if (operations.length == 0) return eventStream
let operation = operations.shift()
return FRP.compose(operation(eventStream), ...operations)
}
FRP.stepper = function(eventStream, initial) {
let valueAtLastStep = initial
eventStream(function nextStep(value) {
valueAtLastStep = value
})
return (function behaveAtLastStep() {
return valueAtLastStep
})
}
FRP.snapshot = function(behavior) {
if (typeof behavior == "function")
return behavior()
return behavior
}
FRP.liftN = function(combine, ...behaviors) {
return function() {
const values = behaviors.map(FRP.snapshot)
return combine(...values)
}
}
FRP.throttle = function(eventStream, ms) {
return function(next) {
let last = 0
eventStream(function(value) {
let now = performance.now()
if (last == 0 || (now - last) > ms) {
next(value)
last = now
}
})
}
}
FRP.hub = function() {
return function(eventStream) {
var nexts = []
var isStarted = false
return function(next) {
nexts.push(next)
if (!isStarted) {
eventStream(function(value) {
nexts.forEach(function(next) {next(value)})
})
isStarted = true
}
}
}
}
export default FRP