ExpressionParser icon indicating copy to clipboard operation
ExpressionParser copied to clipboard

evaluateExpression?

Open tb2johm opened this issue 3 years ago • 3 comments

In the Readme.md under the heading Custom Language it's described how to evaluate an expression (with new ExpressionParser(arithmeticLanguage).evaluateExpression(expr)).

However I can't get this to work. Looking in the code I can't even see any evaluateExpression.

Have I misunderstood something, or is the documentation faulty?

tb2johm avatar Sep 06 '22 09:09 tb2johm

it's called expressionToValue, docs seem to be faulty

j4k0xb avatar Sep 07 '22 00:09 j4k0xb

yes it's expressionToValue, but then it complains about types are not explicitly written (Parameter 'a' implicitly has an 'any' type), and when I fix that it says that 'ExpressionThunk' is not assignable to type 'number'

andras-gyarmati avatar Dec 07 '23 14:12 andras-gyarmati

theres no way of specifying the thunk/term types don't think you can do much about it other than cast, ts-ignore or runtime checks

const arithmeticLanguage: ExpressionParserOptions = {
  INFIX_OPS: {
    "+": function (a, b) {
      return (a() as number) + (b() as number);
    },

j4k0xb avatar Dec 10 '23 16:12 j4k0xb

Thankyou

Fixed expressionToValue in README.md

dcollien avatar Mar 12 '25 01:03 dcollien

I also exported the helpers used in the demo language:

import {
  array,
  char,
  evalArray,
  evalBool,
  evalString,
  iterable,
  num,
  obj,
  string,
  unpackArgs,
}

which can help with typing, and error handling on incorrect types

e.g. in formula.ts

    ADD: (a, b) => num(a()) + num(b()),
    SUB: (a, b) => num(a()) - num(b()),
    MUL: (a, b) => num(a()) * num(b()),
    DIV: (a, b) => num(a()) / num(b()),

...

    SUM: (arg) =>
      evalArray(arg(), num).reduce((prev: number, curr) => prev + num(curr), 0),

(Note these go through unpackArgs)

dcollien avatar Mar 20 '25 08:03 dcollien