I have a mathjs function in react. What it does is evaluate formulas using the values from the variables. e.g
var variables = {'A': 1, 'B': 2}
var formula = 'A > 0 or B < 5'
math.evaluate(formula, variables) // this will return true
But when comparing string it returns cannot Error: Cannot convert "abc" to a number
var variables = {'A': 'abc'}
var formula = 'A == "abc"'
math.evaluate(formula, variables) // this will return Error: Cannot convert "abc" to a number
Can anyone guide me on how should I do this. Thanks. Any question similar to this will be appreciated as well. I tried to search couldnt get much.
I have tried the following. It doesnt override the function https://github.com/josdejong/mathjs/issues/1051#issuecomment-369930811
The == operator (function math.equal) and other comparison functions only work for numeric comparisons. String input is converted into a number, so that for example "2" < "10" evaluates to true, like you would expect in a mathematical context (whilst JavaScript returns false here).
If you want to compare strings, you can use the function equalText.
If i use equalText or compareText I get the following error
Uncaught TypeError: Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: Object, index: 1)
Is there a way to compare the text from an object instead?
What is "the" text of an object in your case? Can you show what you try to do?
This is what I am actually trying to do.
formula = ' A >= 2 and B == "year" '
variables = { A: 23, B: 'year' }
import { evaluate } from 'mathjs'
const MATH_EVAL = (formula, variables)=> {
var result = evaluate(formula, variables)
return result
}
export default MATH_EVAL
I had no issue when the variables were numbers only.
P.S
Tried with both '==' and '==='
hm, this example from https://github.com/josdejong/mathjs/issues/1051#issuecomment-369930811 importing your own version of relational functions indeed doesn't work anymore. I will work out a new example.
@anasyo10 I've created an example for this: examples/advanced/custom_relational_functions.js. Can you have a look at that and see if it makes sense and solves your issue?
The main difference is that the created functions don't update their dependencies anymore when you replace an existing function with a new one. I have to give that some more thought, maybe we can make this work when working with a mathjs instance (instead of pure functions).
@josdejong thanks ALOT, this worked.
Most helpful comment
@anasyo10 I've created an example for this: examples/advanced/custom_relational_functions.js. Can you have a look at that and see if it makes sense and solves your issue?
The main difference is that the created functions don't update their dependencies anymore when you replace an existing function with a new one. I have to give that some more thought, maybe we can make this work when working with a mathjs instance (instead of pure functions).