Skip to content

Instantly share code, notes, and snippets.

@twilson63
Created May 24, 2017 00:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twilson63/f4997b90c63743e8d12c1d5583e97ecd to your computer and use it in GitHub Desktop.
Save twilson63/f4997b90c63743e8d12c1d5583e97ecd to your computer and use it in GitHub Desktop.
"use strict";
/**
* Name: Calculator
* Author: Tom Wilson
* Description: This is a calculator engine that provides the ability to
* set the operators functions that will be used in the calculation process
* this gives the student the ability to create the operator functions of the
* calculator process, without having to worry about the engine.
* The main calc method takes a string as an equation:
*
* Calculator.calc('1 + 1')
*
* If you have your operators set, the engine should work fine.
*/
(function (window) {
window.Calculator = {
setOperator: setOperator,
calc: calculate
};
var methods = {};
function calculate(expr) {
return expr.split(' ').reduce(calc, 0);
}
function calc(acc, x) {
if (x === '+' && isNumber(acc)) {
return methods.ADD(parseInt(acc, 10));
}
if (x === '-' && isNumber(acc)) {
return methods.MINUS(parseInt(acc, 10));
}
if (x === '*' && isNumber(acc)) {
return methods.TIMES(parseInt(acc, 10));
}
if (x === '/' && isNumber(acc)) {
return methods.DIVIDE(parseInt(acc, 10));
}
if (isFunction(acc)) {
return acc(parseInt(x, 10));
}
return x;
}
function setOperator(operator, fn) {
// check if valid operator
if (/(\+|\-|\*|\/)/.test(operator) === false) {
throw new Error('Operator must be either + or - or * or /');
}
if (operator === '+') {
methods.ADD = curry(fn);
} else if (operator === '-') {
methods.MINUS = curry(fn);
} else if (operator === '*') {
methods.TIMES = curry(fn);
} else if (operator === '/') {
methods.DIVIDE = curry(fn);
}
}
function isNumber(v) {
v = parseInt(v, 10);
return typeof v === 'number' ? true : false;
}
function isFunction(v) {
return typeof v === 'function' ? true : false;
}
function curry(fn) {
return function (a) {
return function (b) {
return fn(a, b);
};
};
}
})(window);
// usage example
/*
Calculator.setOperator('+', function (a,b) {
return a + b
})
Calculator.setOperator('-', function (a,b) {
return a - b
})
Calculator.enter('12 + 12') // 24
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment