Skip to content

Instantly share code, notes, and snippets.

@tjstebbing
Created June 7, 2021 23:02
Show Gist options
  • Save tjstebbing/a9df343ed00e746601f783da014a003c to your computer and use it in GitHub Desktop.
Save tjstebbing/a9df343ed00e746601f783da014a003c to your computer and use it in GitHub Desktop.
const fnCache: { [key: string]: any } = {}
function scriptValue(input: string, args: { [key: string]: any }): Function {
let params: string[] = []
let vals: any[] = []
for (let k in args) {
params.push(k)
vals.push(args[k])
}
let keys = params.join(',')
let fnKey = keys + input
if (!fnCache[fnKey]) {
fnCache[fnKey] = Function(
'"use strict";return (function(' + keys + '){ return ' + input + '})',
)()
}
try {
return fnCache[fnKey](...vals)
} catch (e) {
console.error(
`scriptValue error: '${e}' in expression: '${input}' with ctx: '${JSON.stringify(
args,
)}'`,
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment