Skip to content

Instantly share code, notes, and snippets.

@mwoods79
Created December 5, 2012 06:52
Show Gist options
  • Save mwoods79/4213166 to your computer and use it in GitHub Desktop.
Save mwoods79/4213166 to your computer and use it in GitHub Desktop.
Functional Programming A Calculator In Javascript
// 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;
});
}
calculate(" 2 + 2.5 * 2 ") // returns 7
calculate("12 / 6 + 4 * 3") // returns 14
@audrenbdb
Copy link

audrenbdb commented Nov 8, 2020

It's not pure if you push to an array
here's a functional way I made : https://gist.github.com/audrenbdb/94fcaa1e17a8e5db8166c04927259d40

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment