Functional Reactive Programming
What's wrong with this code?
function run(array) {
let sum = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] > 10) {
sum += array[i] * 2;
}
}
return sum;
}
function run(array) {
return array
.filter(a => a > 10)
.map(a => a * 2)
.reduce((a, b) => a + b, 0);
}
An example of working with events
let clicks = 0;
document.addEventListener('click', function onClick(e) {
if (clicks < 10) {
if (e.clientX > window.innerWidth / 2) {
console.log(e.clientX);
clicks++;
}
} else {
document.removeEventListener('click', onClick);
}
});
let clicks = 0;
let waiting = false;
document.addEventListener('click', function onClick(e) {
if (clicks < 10) {
if (!waiting) {
if (e.clientX > window.innerWidth / 2) {
waiting = true;
setTimeout(() => {
console.log(e.clientX);
clicks++;
waiting = false;
}, 1000);
}
}
} else {
document.removeEventListener('click', onClick);
}
});
What's an observable?
- A stream or sequence of ongoing events ordered in time
- We can create new streams by calling higher-order functions such as map, filter, scan, etc
function listen(element, eventName) {
return new Observable(observer => {
// Create an event handler which sends data to the sink
let handler = event => observer.next(event);
// Attach the event handler
element.addEventListener(eventName, handler, true);
// Return a cleanup function which will cancel the event stream
return () => {
// Detach the event handler from the element
element.removeEventListener(eventName, handler, true);
};
});
}
// Return an observable of special key down commands
function commandKeys(element) {
let keyCommands = { "38": "up", "40": "down" };
return listen(element, "keydown")
.filter(event => event.keyCode in keyCommands)
.map(event => keyCommands[event.keyCode])
}
Let's get our hands dirty
Live coding time (wish me luck)!
A large example
More live coding! (woohoo!)
The end
Functional Reactive Programming
By Ronen Amiel
Functional Reactive Programming
- 583