Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created May 30, 2017 23:56
Show Gist options
  • Save alejandrolechuga/0869cf16852a1b5017189e9c70895b56 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/0869cf16852a1b5017189e9c70895b56 to your computer and use it in GitHub Desktop.
//////////////////////////////////////////////////////////////
//
// Question 3:
//
// Implement a basic calculator to evaluate a simple expression string.
//
// The expression string may contain the plus +, minus sign -,
// non-negative integers and empty spaces.
//
// You may assume that the given expression is always valid.
//
// Some examples:
// "1 + 1" = 2
// " 2-1 + 2 " = 3
//
// Note:
// * Do not use the eval built-in library function.
//
///////////////////////////////////////////////////////////////
function calculator(expression) {
var operator = '';
return Array.from(expression).reduce(function (acc, character) {
var number = parseInt(character);
if (character === ' ') {
return acc;
}
if (isNaN(number) ) {
operator = character;
} else if (operator.length > 0) {
switch(operator) {
case '+':
acc = acc + number;
break;
case '-':
acc = acc - number;
break;
}
} else {
acc = number;
}
return acc;
}, 0);
}
console.log(calculator("1 + 1"));
console.log(calculator(" 2-1 + 2 "));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment