I've been trying to make the following IIFE functional as a NightBot !math command.
(() => {// const input = '$(query)';const input = '1,354,280 * .7';if (/[a-z]/gi.test(input))return 'Equation cannot contain letters';const cleanedInput: string = input.replace(/,+/g, '');let mathResult: number = Function(`'use strict';return (${cleanedInput});`)();mathResult = Math.trunc(mathResult * 100) / 100;let textResult: string;const [digits, ...decimals] = mathResult.toString().split('.');const commaSeparated: string = digits.split('').reverse().map((v, i, a) => i !== a.length - 1 && (i + 1) % 3 === 0 ? `,${v}` : v).reverse().join('');textResult = `${commaSeparated}`;if (decimals?.length)textResult += `.${decimals.join('')}`;textResult = `${input} = ${textResult}`;console.log(textResult);// return textResult;})();
but I'm struggling to find a way around the error I'm running into that is quoted in the title.
Most of the posts surrounding this error involve urlFetch which I'm not using.
Really I'm just looking for suggestions on how to possibly proceed here.
I understand the offending line is
let mathResult: number = Function('use strict';return (${cleanedInput});)();because I'm trying to programmatically generate a function to use during runtime.
Is there any kind of alternative to this behaviour? Maybe some NightBot functionality I'm unaware of? Or maybe a different way to accomplish the same functionality in JS that NightBot permits?
Maybe with the current approach it's not possible and I'd have to write a more manual math equation parser and not lean on the JS language interpreting and doing the heavy lifting for me?