Check if a variable is of function type

后端 未结 18 1432
北海茫月
北海茫月 2020-11-22 15:37

Suppose I have any variable, which is defined as follows:

var a = function() {/* Statements */};

I want a function which checks if the type

18条回答
  •  孤街浪徒
    2020-11-22 16:28

    For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

    Next code contains only pure and pointfree functions:

    const R = require('ramda');
    
    const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
    
    const equalsSyncFunction = isPrototypeEquals(() => {});
    
    const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
    

    As of ES2017, async functions are available, so we can check against them as well:

    const equalsAsyncFunction = isPrototypeEquals(async () => {});
    
    const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
    

    And then combine them together:

    const isFunction = R.either(isSyncFunction, isAsyncFunction);
    

    Of course, function should be protected against null and undefined values, so to make it "safe":

    const safeIsFunction = R.unless(R.isNil, isFunction);
    

    And, complete snippet to sum up:

    const R = require('ramda');
    
    const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
    
    const equalsSyncFunction = isPrototypeEquals(() => {});
    const equalsAsyncFunction = isPrototypeEquals(async () => {});
    
    const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
    const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
    
    const isFunction = R.either(isSyncFunction, isAsyncFunction);
    
    const safeIsFunction = R.unless(R.isNil, isFunction);
    
    // ---
    
    console.log(safeIsFunction( function () {} ));
    console.log(safeIsFunction( () => {} ));
    console.log(safeIsFunction( (async () => {}) ));
    console.log(safeIsFunction( new class {} ));
    console.log(safeIsFunction( {} ));
    console.log(safeIsFunction( [] ));
    console.log(safeIsFunction( 'a' ));
    console.log(safeIsFunction( 1 ));
    console.log(safeIsFunction( null ));
    console.log(safeIsFunction( undefined ));
    

    However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

提交回复
热议问题