前端面试-手写compose 函数

date
Nov 20, 2022
slug
write-function-conpose
status
Published
tags
Interview
summary
write function compose
type
Post

常规面试题 - 手写compose 函数

 
// 实现简单的compose函数,可以将多个函数组合为一个函数执行
function myCompose(...fns){
    var len = fns.length;
    for(var i = 0; i < len; i++){
        // 防止传入的不是函数
        if(typeof fns[i] !== 'function'){
            throw new TypeError('Expect arguments are function')
        }
    }

    function componse(...args){
        var index = 0;
        // 如果没有传入函数,则直接返回参数,如果有传入函数,则执行第一个函数,并且将结果返回
        var result = len ? fns[index].apply(this, args) : args;
        // 依次执行后续函数并且将结果返回
        while(++index < len){
            // 由于函数返回值通常为一个,这里使用call会更加适合
            result = fns[index].call(this,result)
        }
        return result
    }
    return componse;

}

function double(num){
    return num * 2
}

function square(num){
    return num ** 2
}

var componsedFn = myCompose(double, square)
console.log(componsedFn(10))
 

© xk_wan 2021 - 2024