Skip to content

Commit 9cc6ca4

Browse files
Fix string/number concatenation with add operator (#23)
* Fix string/number concatenation with add operator * Add unit tests for sub, mul, div, mod, and pow operators
1 parent 0a7ef50 commit 9cc6ca4

4 files changed

Lines changed: 475 additions & 18 deletions

File tree

src/operators/binary/arithmetic.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,21 @@ export function add(a: any, b: any): any {
1414
return a + b;
1515
}
1616

17-
// If both values are strings and at least one of them is a non-number
18-
// then we want to concatenate the strings.
19-
if (typeof a === 'string' && typeof b === 'string') {
17+
// If one of the values is a string and both are either string or number, try to add or else concatenate.
18+
if (
19+
(typeof a === 'string' || typeof b === 'string') &&
20+
(typeof a === 'string' || typeof a === 'number') &&
21+
(typeof b === 'string' || typeof b === 'number')
22+
) {
2023
const numA = Number(a);
2124
const numB = Number(b);
2225

2326
if (isNaN(numA) || isNaN(numB)) {
2427
return `${a}${b}`;
2528
}
29+
30+
// If both values can be converted to numbers then we want to add the numbers.
31+
return numA + numB;
2632
}
2733

2834
// If both values are arrays then we want to concatenate the arrays.
@@ -40,11 +46,6 @@ export function add(a: any, b: any): any {
4046
return { ...a, ...b };
4147
}
4248

43-
// If both values can be converted to numbers then we want to add the numbers.
44-
if (!isNaN(Number(a)) && !isNaN(Number(b))) {
45-
return Number(a) + Number(b);
46-
}
47-
4849
// Otherwise return an error indicating that the values of mixed types cannot be added.
4950
throw new Error(`Cannot add values of incompatible types: ${typeof a} and ${typeof b}`);
5051
}

test/functions/functions-binary-ops.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@ describe('Binary Operators TypeScript Test', function () {
4949
const parser = new Parser();
5050
assert.deepStrictEqual(parser.evaluate('null + null'), {});
5151
});
52-
it('should convert numeric values to numbers before adding', function () {
52+
it('should throw error for boolean operands', function () {
5353
const parser = new Parser();
54-
assert.strictEqual(parser.evaluate('true + 1'), 2);
55-
assert.strictEqual(parser.evaluate('false + 5'), 5);
56-
assert.strictEqual(parser.evaluate('1 + true'), 2);
54+
assert.throws(() => parser.evaluate('true + 1'), /Cannot add values of incompatible types/);
55+
assert.throws(() => parser.evaluate('false + 5'), /Cannot add values of incompatible types/);
56+
assert.throws(() => parser.evaluate('1 + true'), /Cannot add values of incompatible types/);
5757
});
5858
it('should throw error for incompatible types', function () {
5959
const parser = new Parser();

0 commit comments

Comments
 (0)