2022-02-04 19:00:08 +01:00
|
|
|
import { Variable } from 'models'
|
2022-03-07 09:48:10 +01:00
|
|
|
import { isDefined, isNotDefined } from 'utils'
|
2022-01-14 07:49:24 +01:00
|
|
|
|
|
|
|
export const stringContainsVariable = (str: string): boolean =>
|
|
|
|
/\{\{(.*?)\}\}/g.test(str)
|
|
|
|
|
2022-02-07 18:06:37 +01:00
|
|
|
export const parseVariables =
|
2022-03-31 16:41:18 +02:00
|
|
|
(
|
|
|
|
variables: Variable[],
|
|
|
|
options: { fieldToParse: 'value' | 'id' } = { fieldToParse: 'value' }
|
|
|
|
) =>
|
|
|
|
(text: string | undefined): string => {
|
2022-02-07 18:06:37 +01:00
|
|
|
if (!text || text === '') return ''
|
|
|
|
return text.replace(/\{\{(.*?)\}\}/g, (_, fullVariableString) => {
|
|
|
|
const matchedVarName = fullVariableString.replace(/{{|}}/g, '')
|
2022-03-31 16:41:18 +02:00
|
|
|
const variable = variables.find((v) => {
|
|
|
|
return matchedVarName === v.name && isDefined(v.value)
|
|
|
|
})
|
|
|
|
if (!variable) return ''
|
2022-02-07 18:06:37 +01:00
|
|
|
return (
|
2022-04-08 18:07:14 -05:00
|
|
|
(options.fieldToParse === 'value'
|
|
|
|
? variable.value?.toString()
|
|
|
|
: variable.id) || ''
|
2022-02-07 18:06:37 +01:00
|
|
|
)
|
|
|
|
})
|
|
|
|
}
|
2022-01-14 07:49:24 +01:00
|
|
|
|
2022-03-31 16:41:18 +02:00
|
|
|
export const evaluateExpression = (variables: Variable[]) => (str: string) => {
|
2022-01-14 07:49:24 +01:00
|
|
|
try {
|
2022-03-31 16:41:18 +02:00
|
|
|
const func = Function(
|
|
|
|
...variables.map((v) => v.id),
|
|
|
|
parseVariables(variables, { fieldToParse: 'id' })(
|
|
|
|
str.includes('return ') ? str : `return ${str}`
|
|
|
|
)
|
|
|
|
)
|
|
|
|
const evaluatedResult = func(...variables.map((v) => v.value))
|
2022-04-08 18:07:14 -05:00
|
|
|
return isNotDefined(evaluatedResult) ? '' : evaluatedResult
|
2022-01-14 07:49:24 +01:00
|
|
|
} catch (err) {
|
2022-03-07 09:48:10 +01:00
|
|
|
console.log(err)
|
2022-03-02 18:58:10 +01:00
|
|
|
return str
|
2022-01-14 07:49:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-19 14:25:15 +01:00
|
|
|
export const parseVariablesInObject = (
|
|
|
|
object: { [key: string]: string | number },
|
2022-02-04 19:00:08 +01:00
|
|
|
variables: Variable[]
|
2022-01-19 14:25:15 +01:00
|
|
|
) =>
|
|
|
|
Object.keys(object).reduce((newObj, key) => {
|
|
|
|
const currentValue = object[key]
|
|
|
|
return {
|
|
|
|
...newObj,
|
|
|
|
[key]:
|
|
|
|
typeof currentValue === 'string'
|
2022-02-07 18:06:37 +01:00
|
|
|
? parseVariables(variables)(currentValue)
|
2022-01-19 14:25:15 +01:00
|
|
|
: currentValue,
|
|
|
|
}
|
|
|
|
}, {})
|