1.這里說得fn個(gè)參數(shù),我知道應(yīng)該跟arguments和在函數(shù)里面用return function(){}這種方式來寫,但是就是寫不明白
function add(a,b){
return a+b;
}
function square(a){
return a*a;
}
function plusOne(c){
return c+1;
}
//var result = plusOne(square(add(1,2))); //這種的直接的轉(zhuǎn)化成下面的不會(huì)
//alert(result);
var addSquareAndPlusOne = composite(add,square,plusOne);
function composite(add,square,plusOne){
return function(){
//這里怎么寫呢?謝謝指導(dǎo)
}
}
addSquareAndPlusOne(1,2);
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
第一種寫法:
const composite = (...args) => {
return (...arguments) => {
return args.reduce((memo, current) => {
return current(typeof memo === 'function' ? memo.apply(memo, arguments) : memo)
})
}
}
第二種寫法:
const composite = (...args) => {
return (...arguments) => {
const init = args[0].apply(null, arguments)
return args.slice(1).reduce((memo, current) => {
return current(memo)
}, init)
}
}
改進(jìn)了一下 @小明 的代碼,現(xiàn)在可以隨意改變需要執(zhí)行方法的順序了,只需要保證有足夠的參數(shù)就可以了
var composite = (...opts) => (...args)=>opts.reduce((curr, opt)=>[opt.apply(opt, curr), ...curr.slice(opt.length)], args)[0];
composite(add,square,plusOne)(1,2); // 10
composite(square,plusOne,add)(1,2); // 4
function add(a,b){
return a+b;
}
function square(a){
return a*a;
}
function plusOne(c){
return c+1;
}
// plusOne(square(add()))
var addSquareAndPlusOne = composite(add,square,plusOne);
function composite(){
var slice = Array.prototype.slice,
fns = slice.call(arguments),
fnl = fns.length;
if(fnl === 0) return null;
return function () {
var i = 1, ret = null;
// console.log(fns,fnl)
if(fnl > 2) {
while(i < fnl) {
// console.log(i)
ret = i === 1 ? fns[i](fns[i - 1].apply(null, arguments)) : fns[i](ret);
i++;
}
return ret;
} else {
return fns[0].apply(null, arguments);
}
}
}
addSquareAndPlusOne(1,2);
我也來貼一個(gè)比較low的的寫法,希望多多指正
var startParam=null;
var o={
f1:function (a,b){
return (a+b);
},
f2:function (a,b){
return (a-b);
},
f3:function (a,b){
return (a*b);
}
};
function composite(fa,fb,fc){
var args=arguments;
for(var i=0;i<arguments.length;i++){
if(i==0){
(function(i){
o['f'+(i+1)]=function(){
return (startParam=args[i].apply(undefined,arguments));
}})(i)
}else{
(function(i){
o['f'+(i+1)]=function(){
return (startParam=args[i].apply(undefined,[startParam].concat([].slice.call(arguments))));
}})(i)
}
}
}
composite(o.f1,o.f2,o.f3)
alert(o.f1(1,1));
alert(o.f2(3));
alert(o.f3(4));
把 @止水 同學(xué)的兩種寫法結(jié)合一下:
const composite = (...args) => {
return (...arguments) => {
return args.reduce((memo, current) => current.apply(current, [].concat(memo)), arguments)
}
}