public
Created

Calculate simple maths questions

  • Download Gist
javascript_math_calculator.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
exports.calculate = function(query) {
var result = 0;
var regRes = query.match(/what is ([0-9]+) ([a-z ]+) ([0-9]+) ([a-z ]+) (.*)/)
var num3 = null;
if (regRes !== null && regRes.length > (3 + 1)) {
var op2 = regRes[4].trim();
num3 = regRes[5];
}
 
regRes = query.match(/what is ([0-9]+) ([a-z ]+)([0-9]+)/)
 
var num1 = regRes[1]
var op = regRes[2].trim()
var num2 = regRes[3]
 
result = calcTwoNumbers(num1, op, num2);
if (num3 != null) {
result = calcTwoNumbers(result, op2, num3);
}
return result;
}
 
function calcTwoNumbers(num1, op, num2) {
var result = 0;
switch (op) {
case 'plus':
result += Number(num1) + Number(num2)
break;
case 'minus':
result += Number(num1) - Number(num2)
break;
case 'multiplied by':
result += Number(num1) * Number(num2)
break;
case 'divided by':
result += Number(num1) / Number(num2)
break;
}
return result;
}
 
// Some tests
console.log("plus = " + (30 == exports.calculate("what is 12 plus 18") ))
console.log("wrong plus = " + (30 != exports.calculate("what is 10 plus 3") ))
console.log("minus = " + (10 == exports.calculate("what is 12 minus 2")))
console.log("multiplied = " + (10 == exports.calculate("what is 2 multiplied by 5")))
console.log("divided = " + (2 == exports.calculate("what is 10 divided by 5")))
console.log("plus minus = " + (30 == exports.calculate("what is 35 plus 5 minus 10")))
console.log("plus multiply = " + (25 == exports.calculate("what is 2 plus 3 multiplied by 5")))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.