Created
December 4, 2013 18:28
-
-
Save edalorzo/7792857 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Value(value){ | |
this.value = value || 0; | |
} | |
Value.prototype.eval = function(){ return this; }; | |
Value.prototype.valueOf = function(){ return this.value.valueOf(); }; | |
Value.prototype.toString = function(){ return this.value.toString(); }; | |
var createOperator = function(){ | |
function reduce(oper){ | |
return new Value(oper.apply(null, this.expressions.map(function(expr){ return expr.eval();}))); | |
} | |
function toString(name){ | |
return this.expressions.map(function(expr){ return expr.toString();}).join(' ' + name + ' '); | |
} | |
return function(name, oper){ | |
return function(){ | |
this.expressions = [].slice.call(arguments); | |
this.eval = reduce.bind(this,oper); | |
this.toString = toString.bind(this,name); | |
}; | |
}; | |
}(); | |
var Add = createOperator("+", function(a,b){ return a + b;}); | |
var Sub = createOperator("-", function(a,b){ return a - b;}); | |
var Mul = createOperator("*", function(a,b){ return a * b;}); | |
var Div = createOperator("/", function(a,b){ return a / b;}); | |
var Exp = createOperator("^", function(a,b){ return Math.pow(a,b);}); | |
describe("Kata Test Suite", function(){ | |
it("should evaluate expressions", function(){ | |
var exp = new Add(new Mul(new Value(3),new Value(5)),new Sub(new Mul(new Div(new Value(6),new Value(2)) ,new Exp(new Value(10),new Value(2))), new Value(273))); | |
Test.assertEquals(exp.toString(), "3 * 5 + 6 / 2 * 10 ^ 2 - 273"); | |
Test.assertEquals(exp.eval().valueOf(), 42); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment