Skip to content

Commit

Permalink
fix: math allow negative sign at biginning
Browse files Browse the repository at this point in the history
  • Loading branch information
hhow09 committed Jan 23, 2025
1 parent 0ed5868 commit b807559
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
4 changes: 3 additions & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 4 additions & 1 deletion backend/src/math/evaluate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
9 changes: 6 additions & 3 deletions backend/src/math/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down

0 comments on commit b807559

Please sign in to comment.