Improved math expressions (#6)

* Improved math expressions

Things are in a better state, + - / * work now for basic const var = 5 <operator> 1

Though the current method I'm using to make the ast isn't really going to work for dealing with precedence rules so some refactoring is needed going forward

* get complex math expressions working with precedence including parans

Node that identifiers are working, call expressions are not, that's a TODO
/ * % + - are working both other things like exponent and logical operators are also not working.
Recasting is the most important thing to implement next

* get recasting working for nested binary expressions

* clean up
This commit is contained in:
Kurt Hutten
2023-01-21 21:23:01 +11:00
committed by GitHub
parent d61c003f82
commit e37f68424b
8 changed files with 955 additions and 25 deletions

View File

@ -296,6 +296,63 @@ show(mySketch)
})
})
describe('testing math operators', () => {
it('it can sum', () => {
const code = ['const myVar = 1 + 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(3)
})
it('it can subtract', () => {
const code = ['const myVar = 1 - 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(-1)
})
it('it can multiply', () => {
const code = ['const myVar = 1 * 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(2)
})
it('it can divide', () => {
const code = ['const myVar = 1 / 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(0.5)
})
it('it can modulus', () => {
const code = ['const myVar = 5 % 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(1)
})
it('it can do multiple operations', () => {
const code = ['const myVar = 1 + 2 * 3'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(7)
})
it('big example with parans', () => {
const code = ['const myVar = 1 + 2 * (3 - 4) / -5 + 6'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(7.4)
})
it('with identifier', () => {
const code = ['const yo = 6', 'const myVar = yo / 2'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(3)
})
it('with identifier', () => {
const code = ['const myVar = 2 * ((2 + 3 ) / 4 + 5)'].join('\n')
const { root } = exe(code)
expect(root.myVar.value).toBe(12.5)
})
// TODO
// it('with callExpression', () => {
// const code = [
// 'const yo = (a) => a * 2',
// 'const myVar = yo(2) + 2'
// ].join('\n')
// const { root } = exe(code)
// expect(root.myVar.value).toBe(6)
// })
})
// helpers
function exe(