Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created January 23, 2012 03:04
Show Gist options
  • Save mxriverlynn/1660207 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1660207 to your computer and use it in GitHub Desktop.
functional js calculator
var one = value(1);
var two = value(2);
var three = value(3);
var four = value(4);
// (1 + 2) * 3 - 4 == 5
var added = add(one, two)
var multiplied = multiply(added, three)
var resultFunc = subtract(multiplied, four);
// the result is the same.
// it's been composed the same, functionally
// it was just put together with more variables in the mix
var result = resultFunc();
consol.log(result); // => 5
// A raw value, represented as a function
var value = function(val){
return function(){
return val;
}
}
// A function to add two functions together
var add = function(x, y){
return function(){
return x() + y();
}
}
// A function to subtract one function from another
var subtract = function(x, y){
return function(){
return x() - y();
}
}
// A function to multiply two functions
var multiply = function(x, y){
return function(){
return x() * y();
}
}
/**
Prototypal
from Oscar Godson: http://jsbin.com/atopek/edit#javascript
*/
var Calc = function(){
this.sum = 0; //could be a param
return this;
}
Calc.prototype.add = function(x){
this.sum = this.sum + x;
return this;
}
Calc.prototype.multiply = function(x){
this.sum = this.sum * x
return this;
}
Calc.prototype.subtract = function(x){
this.sum = this.sum - x;
return this
}
Calc.prototype.result = function(){
return this.sum;
}
console.log(new Calc().add(1).add(2).multiply(3).subtract(4).result())
var one = value(1);
var two = value(2);
var three = value(3);
var four = value(4);
// (1 + 2) * 3 - 4 == 5
var resultFunc = subtract(multiply(add(one, two), three), four);
// but it's still a function right now, so evaluate it
var result = resultFunc();
consol.log(result); // => 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment