js 偏函数
在 js 函数中,有一种函数叫偏函数( 左倾 ),其原理是将一些函数组合封装到一个函数中,调用时可以按顺序实现全部功能。
1 function toUpperCase(str){ 2 return str.toUpperCase(); // 将字符串变成大写 3 } 4 5 function add(str){ 6 return str + '!!!'; // 将字符串拼接 7 } 8 9 function split(str){ 10 return str.split(''); // 将字符串拆分为数组 11 } 12 13 function reverse(arr){ 14 return arr.reverse(); // 将数组逆序 15 } 16 17 function join(arr){ 18 return arr.join('-'); // 将数组按'-'拼接成字符串 19 } 20 21 function compose(){ 22 var args = Array.prototype.slice.call(arguments); // 类数组转换为数组 23 var len = args.length - 1; // 最后一个参数的索引 24 return function(x){ 25 var result = args[len](x); // 执行最后一个函数的结果 26 while(len--){ 27 result = args[len](result); // 执行每个函数的结果 28 } 29 return result; 30 } 31 } 32 33 var f = compose(add, join, reverse, split, toUpperCase); 34 console.log( f('cba') ); // A-B-C!!!
在组合函数 compose 中,依次执行 toUpperCase、split、reverse、join、add 实现全部功能。接下来给出更优雅的写法,通过数组自带的方法实现。
1 function compose1(){ 2 var args = Array.prototype.slice.call(arguments); // 转换为数组使用下面的方法 3 return function(x){ 4 return args.reduceRight(function(result, cb){ 5 return cb(result); 6 }, x); 7 } 8 } 9 10 var f = compose1(add, join, reverse, split, toUpperCase); 11 console.log( f('cba') ); // A-B-C!!!
最后用 ES6 的方法实现如下
1 const compose2 = (...args) => x => args.reduceRight((result, cb) => cb(res), x); 2 3 var f = compose2(add, join, reverse, split, toUpperCase); 4 console.log( f('cba') ); // A-B-C!!!
以上就是 js 高阶函数--偏函数的实现方法,希望对大家有所帮助。