dispatch
函数接收多个函数,依次执行直到返回一个非undefined的值。- 返回高阶函数,接收业务函数真正的参数。
var dispatch = (...args) => {
let funs = _.toArray(args),
size = funs.length;
return (...params) => {
let ret = undefined,
funIndex,
fun;
for (funIndex = 0; funIndex < size; funIndex++) {
fun = funs[funIndex];
ret = fun.apply(null, params);
if (ret != null) return ret;
}
ret;
};
};
var stringReverse = (s) => {
return !_.isString(s) ? undefined : s.split('').reverse().join();
};
var rev = dispatch(stringReverse);
rev('abscd');
- 作为代理函数,负责找到适合的函数执行
- 可以替换
switch case
。 - 函数的组合,可以体现出更强大的威力。
var notify = changeView = shutdown = _.identity;
var performCommandHardCoded = (command) => {
let result;
switch(command.type) {
case 'notify':
result = notify(command.message);
break;
case 'join' :
result = changeView(command.target);
break;
default :
alert(command.type);
}
return result;
};
performCommandHardCoded({type : 'notify', message: 'hi'});
performCommandHardCoded({type : 'join', target : 'target'});
var isa = (type, action) => {
return (obj) => {
if (obj.type === type) {
return action(obj)
}
}
};
var performCommand = dispatch(isa('notify', (obj) => obj.message),
isa('join', (obj) => obj.target),
(obj) => alert(obj.type));
performCommand({type:'notify', message : 'notify'});
performCommand({type:'join', target : 'target'});
组合的方式,往往函数的参数,是该函数返回的结果。
var performAdminCommand = dispatch(isa('kill', (obj) => obj.hostname), performCommand);
performAdminCommand({type: 'kill', hostname: 'foo.com'});
performAdminCommand({type:'join', target : 'join target'});