Skip to content

Instantly share code, notes, and snippets.

@GlauberF
Last active December 2, 2021 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GlauberF/a0f9a0712ed5e76e470121a21650653e to your computer and use it in GitHub Desktop.
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.
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