Skip to content

Overriding function using math.import does not override that function when using evaluate function #2350

@Liam-OShea

Description

@Liam-OShea

UPDATE - I made some progress and am able to avoid the error described in this comment, however I am still receiving incorrect output when using evaluate()

--

Hi josdejong! I am enjoying using your library.

Background

I am working on adding the ability to create user-defined calculated columns to a grid of data. I am using MathJS to evaluate an expression in the form of a string representing the calculated column calculation. This string is defined by the user.

Ex:
scope = {PropertyA = 1, PropertyB = 2, PropertyC = 3} // Values in scope defined by data in row being calculated
math.evaluate('PropertyA + max(PropertyA, PropertyB, PropertyC)', scope)

I am having an issue regarding the treatment of null values causing errors when evaluating the expression. Some rows of data may not have a property which is included in the expression, causing an error when evaluate() is called.

I did some research on MathJS treatment of null values and I did find #830 so I understand why I am encountering these issues.

My goal is to have expressions with null values in them treated as excel treats them. For example during simple mathematical operations I would like a null value to be treated as 0 (eg 5 + null -> 5 + 0 = 5), and in functions I would like them to be omitted (eg mean(5, 10, null) = 7.5 rather than 5)

Question

I found #1829 where someone had a similar issue regarding the treatment of null in functions. I followed the pattern laid out by @Big-Gremlin (#1829 (comment)) but it seems to only work when explicitly calling the overridden function, and does not work when that function comes up in .evaluate(expression, scope).

eg.
const scope = {a:1, b:null}
math.evaluate(sum(a, b), scope) // error
math.sum([1, null]) // works, returns 1

  • Is there a way to override a function that is being executed through the evaluate() function?
  • Is there a way to treat a null value as 0 when being worked on by operators, but treat it as null (so that it can possibly be omitted if overriding the function as described above is possible) within a function? (emulate the behaviour of excel)

My current solution is to detect if the value is null, and if so set it as 0 in the evaluate() scope. This handles the math operator side of the problem (+, -, /, *, etc). Then my next step if I cannot figure this out is to parse the string expression for each function and modify the string to remove the null property from the function parameters. This seems a little hacky to me so I am trying to avoid it.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions