JavaScript ES6: Test for arrow function, built-in function, regular function?

后端 未结 10 750
遇见更好的自我
遇见更好的自我 2020-11-27 06:16

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:

10条回答
  •  孤街浪徒
    2020-11-27 06:30

    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?

    • ^ - start at the beginning of the line
    • [ ^{ ]+? - Look through everything that follows until the next pattern (=>), but if you find a { first, it's not a match
    • => - Found => before {, so it's a match

    Problem?

    Leave a comment if you find a case where it doesn't work, and I'll see if we can accommodate.

提交回复
热议问题