完成 compose 函数。它接受任意多个单参函数(只接受一个参数的函数)作为参数,并且返回一个函数。它的作为用:使得类似 f(g(h(a)))这样的函数调用可以简写为 compose(f, g, h)(a)。

function addOne(a) {
    return a + 1;
};

function multiTwo (a) {
    return a*2;
}
function divThree (a) {
    return a/3;
}
function toString (a) {
    return a + '';
}
function split(a) {
    return a.split('');
}

function compose(divThree, multiTwo, addOne, toString, split) {
    // var func_list = [divThree, multiTwo, addOne, toString, split];
    var func_list = new Array();
    console.log('arguments', arguments);
    for (var arg_index in arguments) {
        var func = arguments[arg_index];
        if (typeof func !== 'function') {
            throw "参数:'" + func + "'不是函数"; // throw抛出异常,在throw语句后立即终止, 它后面的语句执行不到,
        }
        func_list.push(func);
    }
    return function(value) {
        func_list.map(function(func_item) {
            value = func_item(value);
        });
        return value;
    }
}
 
console.log(compose(divThree, multiTwo, addOne, toString, split)(666));  //  ["4", "4", "5"]

猜你喜欢

转载自www.cnblogs.com/lvsk/p/12722499.html