From b807559db40fb7fe994eca56b6748d335adb6de0 Mon Sep 17 00:00:00 2001 From: hhow09 Date: Thu, 23 Jan 2025 12:10:22 +0100 Subject: [PATCH] fix: math allow negative sign at biginning --- backend/README.md | 4 +++- backend/src/math/evaluate.spec.ts | 5 ++++- backend/src/math/evaluate.ts | 9 ++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/backend/README.md b/backend/README.md index d9d8d0a..2686043 100644 --- a/backend/README.md +++ b/backend/README.md @@ -18,7 +18,9 @@ npm run test ## Limitations on calculation - All whitespace is ignored, therefore `1 + 2 3` will consider as `1 + 23` -- negative sign in expression is not supported: e.g. `5 * -3` will return error. +- `negative sign` is only allowed at the beginning of an expression but not after multiplication or division + - e.g. `-5*3 + 1` will return `-14` + - e.g. `5 * -3` will return error. - large number will be converted to exponential notation: e.g. `999999999999 * 999999999999` will return `9.99999999998e+23` - default threshold of exponent is `20` - ref: https://mikemcl.github.io/decimal.js/#precision \ No newline at end of file diff --git a/backend/src/math/evaluate.spec.ts b/backend/src/math/evaluate.spec.ts index 9624e4f..bb92091 100644 --- a/backend/src/math/evaluate.spec.ts +++ b/backend/src/math/evaluate.spec.ts @@ -29,7 +29,10 @@ describe('evaluate', () => { { command: '10.5 * 5 / 2.5', expected: '21' }, { command: '.5 + 1', expected: '1.5' }, - + // negative sign at the beginning + { command: '-1', expected: '-1' }, + { command: '-1 + 1', expected: '0' }, + { command: '-5*3 + 1', expected: '-14' }, // Zero cases { command: '0 * 5', expected: '0' }, { command: '0 / 1', expected: '0' }, diff --git a/backend/src/math/evaluate.ts b/backend/src/math/evaluate.ts index 7a56203..b51e2f0 100644 --- a/backend/src/math/evaluate.ts +++ b/backend/src/math/evaluate.ts @@ -18,9 +18,8 @@ function isValidCommand(s: string): boolean { return false; } } - - // operators cannot be at the beginning or end of the string - if (operators.has(s[0]) || operators.has(s[s.length - 1])) { + // operators cannot be at the end of the string + if (operators.has(s[s.length - 1])) { return false; } return true; @@ -50,6 +49,10 @@ const parseExpressionMDs = (s: string): ExpressionMD[] => { const expressions: ExpressionMD[] = []; let currExp = ""; let prevOp = true; + if (s[0] === '-') { + prevOp = false; + s = s.slice(1); + } for (const token of s.split('')) { if (token === '+') { expressions.push(new ExpressionMD(prevOp, currExp));