ohmyform-ui/components/use.math.ts
Teifun2 535c660f59 Fix some issues with Logic
values.hasOwnProperty(term) is needed as the if statement validates to false even if values contains the term  but the value of the term is currently false (yes / no option with default no)
2022-11-14 13:18:01 +01:00

35 lines
700 B
TypeScript

import debug from 'debug'
import { formula, init } from 'expressionparser'
const logger = debug('useMath')
export const useMath = (): ((
expression: string,
values?: { [id: string]: string | number }
) => boolean) => {
return (expression, values) => {
const parser = init(formula, (term: string) => {
if (values.hasOwnProperty(term)) {
return values[term]
}
throw new Error(`Invalid term: ${term}`);
})
try {
return Boolean(parser.expressionToValue(expression))
} catch (e) {
logger(
'failed to calculate %O: %s',
{
expression,
values,
},
e.message
)
throw e
}
}
}