组合函数-基础用法
模板原型
f,g都是函数,都作为一级参数传递。x是被两函数处理的二级参数。 函数作为参数传递的规则:内部由右往左调用函数。首先调用函数g,然后调用函数f,依次类推。
var compose = function ( f, g ) {
return function ( x ) {
return f ( g ( x) ) ;
} ;
} ;
组合函数举例
通过compose函数,将toUpperCase ,exclaim 函数结合,处理任意字符串成为全大写并在尾部加上感叹号。 亮点:exclaim, toUpperCase函数的位置掉换,不影响结果
var toUpperCase = function ( x ) { return x. toUpperCase ( ) ; } ;
var exclaim = function ( x ) { return x + '!' ; } ;
var shout = compose ( exclaim, toUpperCase) ;
shout ( "send in the clowns" ) ;
普通函数实现上面组合功能的弊端
对比组合函数可发现,普通函数实现上,无法清晰知晓shout 内部的操作,代码灵活性,透明性降低,不易读,不便于复用。
var shout = function ( x ) {
return exclaim ( toUpperCase ( x) ) ;
} ;
组合新功能函数:参数增删减、位置调换
添加新的函数参数,达到新的功能 遵循:函数参数"由右往左"执行原则
var lastUpper = compose ( toUpperCase, head, reverse) ;
lastUpper ( [ 'jumpkick' , 'roundhouse' , 'uppercut' ] ) ;
var loudLastUpper = compose ( exclaim, toUpperCase, head, reverse)
loudLastUpper ( [ 'jumpkick' , 'roundhouse' , 'uppercut' ] ) ;
var loudLastUpper = compose ( exclaim, toUpperCase, head, reverse) ;
var last = compose ( head, reverse) ;
var loudLastUpper = compose ( exclaim, toUpperCase, last) ;
var last = compose ( head, reverse) ;
var angry = compose ( exclaim, toUpperCase) ;
var loudLastUpper = compose ( angry, last) ;