-
-
Save joseanpg/1235943 to your computer and use it in GitHub Desktop.
declarative style evaluation.js
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
/* | |
http://twitter.com/#!/bga_/status/116861871423885312 | |
*/ | |
Object.prototype.thunk = function(name, calc) { | |
Object.defineProperty(this,name,{get: function() { | |
var ret = calc(); | |
delete this[name] // memo result | |
this[name] = ret; | |
return ret; | |
},configurable:true}); | |
} | |
var solveQuadraticEquation = function(a, b, c) { | |
with({}) { | |
thunk('D', function(){ return b*b - 4*a*c }); | |
thunk('double_a', function(){return 2*a}); | |
thunk('sqrt_D', function(){return Math.sqrt(D)}); | |
thunk('x1', function(){ return (-b + sqrt_D) / double_a }); | |
thunk('x2', function(){ return (-b - sqrt_D) / double_a }); | |
if(D < 0) | |
return []; | |
else if(D == 0) | |
return [x1]; | |
else | |
return [x1, x2]; | |
} | |
} | |
console.log(solveQuadraticEquation(1, 0, -1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment