3 ms·
> Not required. I was suggesting that the expression could be parsed at runtime. There are various options, with different tradeoffs. Good idea. That might be
by maxloh 2y ago
> Not required. I was suggesting that the expression could be parsed at runtime. There are various options, with different tradeoffs.
Good idea. That might be possible, though not every JavaScript runtime implements Function.prototype.toString. I'm not sure if Node does.
const aFunction = arg => arg.a === arg.b
const aFunctionSrc = aFunction.toString()
console.log(aFunctionSrc) // 'arg => arg.a === arg.b'
const transformedFunctionSrc = transform(aFunctionSrc)
const transformedFunction = new Function(transformedFunctionSrc)
console.log(transformedFunction) // [Function: anonymous]
// Cache the transformed function in a WeakMap
// WeakMap values are garbage collected when their keys are garbage collected
const functionMap = new WeakMap()
functionMap.set(aFunction, transformedFunction)
console.log(functionMap.get(aFunction)) // [Function: anonymous]