Files
typescript-katas/2kyu/evaluate-mathematical-expression/tests.ts
2025-02-05 23:04:53 +01:00

117 lines
2.3 KiB
TypeScript

import { calc, tokenize } from './solution';
import { expect } from "chai";
var tests: [string, number][] = [
['1+1', 2],
['1 - 1', 0],
['1* 1', 1],
['1 /1', 1],
['-123', -123],
['123', 123],
['2 /2+3 * 4.75- -6', 21.25],
['12* 123', 1476],
['2 / (2 + 3) * 4.33 - -6', 7.732],
['(2 + (2 + 2) / 4) * 3', 9],
['(1 - 2) + -(-(-(-4)))', 3],
['((2.33 / (2.9+3.5)*4) - -6)', 7.45625]
];
describe("calc", function () {
it("should evaluate correctly", () => {
tests.forEach(function (m) {
var x = calc(m[0]);
var y = m[1];
expect(x).to.equal(y, 'Expected: "' + m[0] + '" to be ' + y + ' but got ' + x);
});
});
});
describe("tokenize", function () {
it("should tokenize correctly", () => {
expect(tokenize('1 + 1')).to.deep.equal([{
type: 'number',
value: '1'
}, {
type: 'operator',
value: '+'
}, {
type: 'number',
value: '1'
}]);
expect(tokenize('1 - 1')).to.deep.equal([{
type: 'number',
value: '1'
}, {
type: 'operator',
value: '-'
}, {
type: 'number',
value: '1'
}]);
expect(tokenize('1 * 1')).to.deep.equal([{
type: 'number',
value: '1'
}, {
type: 'operator',
value: '*'
}, {
type: 'number',
value: '1'
}]);
expect(tokenize('1 / 1')).to.deep.equal([{
type: 'number',
value: '1'
}, {
type: 'operator',
value: '/'
}, {
type: 'number',
value: '1'
}]);
expect(tokenize('-3.1415')).to.deep.equal([{
type: 'operator',
value: '-'
}, {
type: 'number',
value: '3'
}, {
type: 'decimal',
value: '.'
}, {
type: 'number',
value: '1415'
}]);
expect(tokenize('3.1415')).to.deep.equal([{
type: 'number',
value: '3'
}, {
type: 'decimal',
value: '.'
}, {
type: 'number',
value: '1415'
}]);
expect(tokenize('(3 + 5) / 3')).to.deep.equal([{
type: 'parenthesis',
value: '('
}, {
type: 'number',
value: '3'
}, {
type: 'operator',
value: '+'
}, {
type: 'number',
value: '5'
}, {
type: 'parenthesis',
value: ')'
}, {
type: 'operator',
value: '/'
}, {
type: 'number',
value: '3'
}]);
});
});