Last active
June 25, 2020 00:02
-
-
Save HichamBenjelloun/48fa2049014690960574e87b8e49075f to your computer and use it in GitHub Desktop.
Transforming an arrow function into a regular function in JavaScript
This file contains hidden or 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
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