Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Created November 2, 2013 11:46
Show Gist options
  • Save disolovyov/7278066 to your computer and use it in GitHub Desktop.
Save disolovyov/7278066 to your computer and use it in GitHub Desktop.
Coding Dojo: Functional Reactive Programming with JavaScript
var Signal = function(value) {
this.value = value;
this.callbacks = [];
};
Signal.prototype.setValue = function(value) {
if (value == null) {
return;
}
this.value = value;
for (var i = 0; i < this.callbacks.length; i++) {
var callback = this.callbacks[i];
callback(value);
}
};
Signal.prototype.map = function(fn) {
var childS = new Signal();
if (this.value != null) {
childS.value = fn(this.value);
}
this.callbacks.push(function(newValue) {
childS.setValue(fn(newValue));
});
return childS;
};
Signal.prototype.filter = function(predicate) {
return this.map(function(value) {
if (predicate(value)) {
return value;
}
});
};
Signal.prototype.fold = function(acc, fn) {
var childS = new Signal(acc);
this.callbacks.push(function(value) {
acc = fn(acc, value);
childS.setValue(acc);
});
return childS;
};
Signal.prototype.print = function() {
console.log(this.value);
this.callbacks.push(function(value) {
console.log(value);
});
};
var fromEvent = function(eventName) {
var signal = new Signal();
window.addEventListener(eventName, function(event) {
signal.setValue(event);
});
return signal;
};
// var mouseMoveS = fromEvent('mousemove');
// mouseMoveS.map(function(event) {
// return [event.x, event.y];
// }).filter(function(coords) {
// return coords[0] < 100;
// }).print();
fromEvent('keypress').map(function(event) {
return String.fromCharCode(event.charCode);
}).fold('', function(text, chr) {
return text + chr;
}).print();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FRP</title>
<script src="frp.js"></script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment