帮你精通JS:神奇的array.reduce方法的10个案例( 三 )

案例09. 功能型函数管道// Building-blocks to use for compositionconst double = x => x + x;const triple = x => 3 * x;const quadruple = x => 4 * x;// Function composition enabling pipe functionalityconst pipe = (...functions) => input => functions.reduce((acc, fn) => fn(acc),input);// Composed functions for multiplication of specific valuesconst multiply6 = pipe(double, triple);const multiply9 = pipe(triple, triple);const multiply16 = pipe(quadruple, quadruple);const multiply24 = pipe(double, triple, quadruple);// Usagemultiply6(6); // 36multiply9(9); // 81multiply16(16); // 256multiply24(10); // 240案例10. 使用 reduce实现mapif (!Array.prototype.mapUsingReduce) {Array.prototype.mapUsingReduce = function(callback, thisArg) {return this.reduce(function(mappedArray, currentValue, index, array) {mappedArray[index] = callback.call(thisArg, currentValue, index, array)return mappedArray}, [])}}[1, 2, , 3].mapUsingReduce((currentValue, index, array) => currentValue + index + array.length) // [5, 7, , 10]
【帮你精通JS:神奇的array.reduce方法的10个案例】


推荐阅读