Last active
December 2, 2021 22:26
-
-
Save GlauberF/a0f9a0712ed5e76e470121a21650653e to your computer and use it in GitHub Desktop.
Parse a string function definition and return a function object. Does not use eval. Analisa uma definição de função em string e retorna um objeto de função. Não usa eval.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParseFunctionString { | |
/* Parse a string function definition and return a function object. Does not use eval. | |
* @param {string} str | |
* @return {function} | |
* | |
* Example: | |
* var f = function (x, y) { return x * y; }; | |
* var g = parseFunction(f.toString()); | |
* g(33, 3); //=> 99 | |
*/ | |
parse(str): any { | |
const isAsync = str.trim().startsWith('async'); | |
const fnBodyIdx = str.indexOf('{'); | |
const fnBody = str.substring(fnBodyIdx + 1, str.lastIndexOf('}')); | |
const fnDeclare = str.substring(0, fnBodyIdx); | |
const fnParams = fnDeclare.substring(fnDeclare.indexOf('(') + 1, fnDeclare.lastIndexOf(')')); | |
const args = fnParams.split(','); | |
if (isAsync) { | |
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; | |
function AsyncFn(): any { | |
return AsyncFunction.apply(this, args); | |
} | |
AsyncFn.prototype = AsyncFunction.prototype; | |
// @ts-ignore | |
return new AsyncFn(); | |
} | |
function Fn(): any { | |
return Function.apply(this, args); | |
} | |
Fn.prototype = Function.prototype; | |
return new Fn().bind(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment