wip: parser

This commit is contained in:
2025-02-05 16:59:40 +01:00
parent 857a252fea
commit 69edf86b63
2 changed files with 332 additions and 31 deletions

View File

@@ -1,4 +1,4 @@
import { calc } from './solution';
import { calc, tokenize } from './solution';
import { expect } from "chai";
var tests: [string, number][] = [
@@ -13,12 +13,102 @@ var tests: [string, number][] = [
['2 / (2 + 3) * 4.33 - -6', 7.732],
];
describe("calc", function() {
describe("calc", function () {
it("should evaluate correctly", () => {
tests.forEach(function(m) {
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'
}]);
});
});