is arrow function

Benchmark created on


Setup

function isArrowFnParse(f) {
    if(!(f instanceof Function)) return false;
    let cmmt = {block: false, line: false};
    let insideParams = false;
    f = f.toString(); let len = f.length;
    for(let i=0, ch; i<len; i++){
        ch = f[i];
        if(cmmt.block || cmmt.line){ 
            if(ch === '*' && f[i+1] === '/'){ cmmt.block = false; i++; }
            else if(ch === '\n') cmmt.line = false;
        }
        else if(ch === '/' && f[i+1] === '*'){ cmmt.block = true;  i++; }
        else if(ch === '/' && f[i+1] === '/'){ cmmt.line = true; i++; }
        else if(insideParams){ if(ch === ')') insideParams = false; }
        else if(ch === '(') insideParams = true;
        else if(ch === '=' && f[i+1] === '>') return true;
        else if(ch === '{') return false;
    }
    return false;
}

function isArrowFnRegex(f) {
    if(!(f instanceof Function)) return false;
    f = f.toString();
    f = f.replace(/\s|\/\/.+/g, '');
    f = f.replace(/\/\*.+\*\//g, '');
    f = f.replace(/\(.+|=>.+/g, '');
    return !(f.indexOf('function') !== -1 || f.indexOf('method') !== -1);
}

function customTest(testFn ){
	
	let a = () => {
    console.log(this);
}

a = (a=2)=> a+2;
testFn(a);

class A {
    constructor() {
    }

    method() {

    }
}
a = new A();
testFn(a.method);

let fns = [
    async function(){
        console.log(this);
    },

    function(){
        console.log(this);
    },

    () => {
        console.log(this);
    },
    async () => {
        function a() {};
    },
    function f(/*()=>*/){},
    Math.min,
    a => function b(){},
    function (a="=>"){},
]
for(let i=0; i<fns.length; i++){
    testFn(fns[i]);
}
}

Test runner

Ready to run.

Testing in
TestOps/sec
isArrowFn with regex
customTest(isArrowFnRegex)
ready
isArrowFn with parsing
customTest(isArrowFnParse)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.