Created
December 5, 2012 06:52
-
-
Save mwoods79/4213166 to your computer and use it in GitHub Desktop.
Functional Programming A Calculator In Javascript
This file contains hidden or 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
// found this here, OMG http://net.tutsplus.com/tutorials/javascript-ajax/what-they-didnt-tell-you-about-es5s-array-extras | |
function calculate (calculation) { | |
//build an array containing the individual parts | |
var parts = calculation.match( | |
// digits |operators|whitespace | |
/(?:\-?[\d\.]+)|[-\+\*\/]|\s+/g | |
); | |
//test if everything was matched | |
if( calculation !== parts.join("") ) { | |
throw new Error("couldn't parse calculation") | |
} | |
//remove all whitespace | |
parts = parts.map(Function.prototype.call, String.prototype.trim); | |
parts = parts.filter(Boolean); | |
//build a separate array containing parsed numbers | |
var nums = parts.map(parseFloat); | |
//build another array with all operations reduced to additions | |
var processed = []; | |
for(var i = 0; i < parts.length; i++){ | |
if( nums[i] === nums[i] ){ //nums[i] isn't NaN | |
processed.push( nums[i] ); | |
} else { | |
switch( parts[i] ) { | |
case "+": | |
continue; //ignore | |
case "-": | |
processed.push(nums[++i] * -1); | |
break; | |
case "*": | |
processed.push(processed.pop() * nums[++i]); | |
break; | |
case "/": | |
processed.push(processed.pop() / nums[++i]); | |
break; | |
default: | |
throw new Error("unknown operation: " + parts[i]); | |
} | |
} | |
} | |
//add all numbers and return the result | |
return processed.reduce(function(result, elem){ | |
return result + elem; | |
}); | |
} |
This file contains hidden or 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
calculate(" 2 + 2.5 * 2 ") // returns 7 | |
calculate("12 / 6 + 4 * 3") // returns 14 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's not pure if you push to an array
here's a functional way I made : https://gist.github.com/audrenbdb/94fcaa1e17a8e5db8166c04927259d40