Is there an elegant way to tell Harmony\'s slim arrow functions apart from regular functions and built-in functions?
The Harmony wiki states that:>
Kangax has made a great point. If you wanted perfection, you'd use an AST parser library to determine the function type, but that is likely to be overkill for many of you.
To that end, here's a method to implement using Regular Expressions:
/** Check if function is Arrow Function */
const isArrowFn = (fn) => (typeof fn === 'function') && /^[^{]+?=>/.test(fn.toString());
/* Demo */
const fn = () => {};
const fn2 = function () { return () => 4 }
isArrowFn(fn) // True
isArrowFn(fn2) // False
Logic
This assumes that all non-arrow function blocks must be surrounded by { }. I don't think that there is an environment which would render otherwise, but please let me know if I'm wrong.
Note: The regex is also written with the assumption that the function's => will always be on the first line. This can be easily changed, but again, I can't imagine anything rendering a newline before it.
How does it work?
Problem?
Leave a comment if you find a case where it doesn't work, and I'll see if we can accommodate.