From 3a314dbda0708f4c7627ac19b08a2543c0c4f352 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Thu, 28 Jun 2018 21:27:48 +0200 Subject: [PATCH] Fixed math processor and added tests --- Math/MathProcessor.js | 14 +++++++++----- tests/Math/MathProcessorTest.js | 13 +++++++------ tests/SpecRunner.html | 6 ++---- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/Math/MathProcessor.js b/Math/MathProcessor.js index 0f372f5..ed6e583 100644 --- a/Math/MathProcessor.js +++ b/Math/MathProcessor.js @@ -28,12 +28,14 @@ } } - return stack.pop(); + const result = stack.pop(); + + return !isNaN(parseFloat(result)) && isFinite(result) ? result : null; }; jsOMS.parseValue = function(value) { - return value.indexOf('.') === -1 ? parseInt(value) : parseFloat(value); + return typeof value === 'string' ? (value.indexOf('.') === -1 ? parseInt(value) : parseFloat(value)) : value; } jsOMS.shuntingYard = function(equation) @@ -41,8 +43,8 @@ const stack = []; const operators = { '^': {precedence: 4, order: 1}, - '/': {precedence: 3, order: -1}, '*': {precedence: 3, order: -1}, + '/': {precedence: 3, order: -1}, '+': {precedence: 2, order: -1}, '-': {precedence: 2, order: -1}, }; @@ -51,9 +53,11 @@ equation = equation.replace(/\s+/g, ''); equation = equation.split(/([\+\-\*\/\^\(\)])/).filter(function (n) { return n !== '' }); - let length = equation.length; + const length = equation.length; + let token; + for (let i = 0; i < length; ++i) { - let token = equation[i]; + token = equation[i]; if (!isNaN(parseFloat(token)) && isFinite(token)) { output.push(token); diff --git a/tests/Math/MathProcessorTest.js b/tests/Math/MathProcessorTest.js index 9d77171..eb3aef1 100644 --- a/tests/Math/MathProcessorTest.js +++ b/tests/Math/MathProcessorTest.js @@ -2,11 +2,12 @@ describe('MathProcessorTest', function () { "use strict"; - beforeEach(function () + describe('testEvaluation', function () { + it('Testing formula evaluation', function () + { + expect(jsOMS.mathEvaluate('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 + 1.5')).toBeCloseTo(4.5, 2); + expect(jsOMS.mathEvaluate('invalid')).toBe(null); + }); }); - - afterEach(function () - { - }); -}); +}); \ No newline at end of file diff --git a/tests/SpecRunner.html b/tests/SpecRunner.html index 6d91f81..a9cd115 100644 --- a/tests/SpecRunner.html +++ b/tests/SpecRunner.html @@ -25,10 +25,9 @@ - - + @@ -41,10 +40,9 @@ - - +