JavaScript 自定义函数:compose

JavaScript 自定义函数:compose

<script type="text/javascript"> 
    function compose() {
        var funcs = [];
        var k = 0;
        for (var i = arguments.length - 1; i >= 0; i--) {
            funcs[k++] = arguments[i];
        }
        return function(a) {
            var result = a;
            for (var i = 0; i < funcs.length - 1;i++) {
                result = funcs[i](result);              
            }
            return result;
        }
    }

    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('') }
    split(toString(addOne(multiTwo(divThree(666))))) // => ["4", "4", "5"]

    var testForCompose = compose(split, toString, addOne, multiTwo, divThree);
    console.log(testForCompose(666));
script>

你可能感兴趣的:(Javascript)