const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);
// Functionsconst isNil = o => o == nullconst isFunction = f => !!f && f instanceof Functionconst isFunctionFaster = f => !!f && 'function' === typeof f
class A {}
function basicFnc(){}async function asyncFnc(){}
const arrowFnc = ()=> {}const arrowRFnc = ()=> 1
// Not functionsconst obj = {}const arr = []const str = 'function'const bol = trueconst num = 1const a = new A()
const list = [isFunction,isFunctionFaster,basicFnc,arrowFnc,arrowRFnc,asyncFnc,Array,Date,Object,Number,String,Symbol,A,obj,arr,str,bol,num,a,null,undefined,]
for (const arg of list) {console.log(`${arg} is a function: ${isFunction(arg)}`)}
以下是这些函数的基本基准:
/*** Figure out how long it takes for a method to execute.** @param {Function} method to test* @param {number} iterations number of executions.* @param {Array} args to pass in.* @param {T} context the context to call the method in.* @return {number} the time it took, in milliseconds to execute.*/const bench = (method, list, iterations, context) => {let start = 0const timer = action => {const time = performance.now()switch (action) {case 'start':start = timereturn 0case 'stop':const elapsed = time - startstart = 0return elapseddefault:return time - start}};
const result = []timer('start')list = [...list]for (let i = 0; i < iterations; i++) {for (const args of list) {result.push(method.apply(context, args))}}const elapsed = timer('stop')
console.log(`Called method [${method.name}]`)console.log(`Mean: ${elapsed / iterations}`)console.log(`Exec. time: ${elapsed}`)
return elapsed}
const fnc = () => {}const isFunction = (f) => f && f instanceof Functionconst isFunctionFaster = (f) => f && 'function' === typeof f
class A {}
function basicFnc(){}async function asyncFnc(){}
const arrowFnc = ()=> {}const arrowRFnc = ()=> 1
// Not functionsconst obj = {}const arr = []const str = 'function'const bol = trueconst num = 1const a = new A()
const list = [[isFunction],[basicFnc],[arrowFnc],[arrowRFnc],[asyncFnc],[Array],[Date],[Object],[Number],[String],[Symbol],[A],[obj],[arr],[str],[bol],[num],[a],[null],[undefined],]
const e1 = bench(isFunction, list, 10000)const e2 = bench(isFunctionFaster, list, 10000)
const rate = e2/e1const percent = Math.abs(1 - rate)*100
console.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)