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:
Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method. So new (() => {}) throws a TypeError but otherwise arrows are like functions
Which means, you can test for arrow functions like:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
But the test will also return true for any built-in function, e.g. setTimeout or Math.min.
It sort of works in Firefox if you get the source code and check if it's "native code", but it doesn't seem much reliable nor portable (other browser implementations, NodeJS / iojs):
setTimeout.toSource().indexOf("[native code]") > -1
The small GitHub project node-is-arrow-function relies on RegExp-checks against the function source code, which isn't that neat.
edit: I gave the JavaScript parser acorn a try and it seems to work quite okay - even though it's pretty overkill.
acorn = require("./acorn");
function fn_sample(a,b){
c = (d,e) => d-e;
f = c(--a, b) * (b, a);
return f;
}
function test(fn){
fn = fn || fn_sample;
try {
acorn.parse("(" + fn.toString() + ")", {
ecmaVersion: 6,
onToken: function(token){
if(typeof token.type == "object" && token.type.type == "=>"){
console.log("ArrowFunction found", token);
}
}
});
} catch(e) {
console.log("Error, possibly caused by [native code]");
console.log(e.message);
}
}
exports.test = test;