Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active June 25, 2020 00:02
Show Gist options
  • Save HichamBenjelloun/48fa2049014690960574e87b8e49075f to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/48fa2049014690960574e87b8e49075f to your computer and use it in GitHub Desktop.
Transforming an arrow function into a regular function in JavaScript
const unarrow = arrowFunc => {
const arrowFuncDefinition = arrowFunc.toString();
const hasEnclosingBraces = arrowFuncDefinition.indexOf('}') === arrowFuncDefinition.length - 1;
const newDefinition =
`return function${
hasEnclosingBraces ?
arrowFuncDefinition.replace('=>', '') :
arrowFuncDefinition.replace('=>', '{return ') + '}'
}`;
return new Function(newDefinition)();
};
export default unarrow;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment