Instantly share code, notes, and snippets.

# gdubya/javascript_math_calculator.js Created Aug 19, 2011

Calculate simple maths questions
 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")))
to join this conversation on GitHub. Already have an account? Sign in to comment