curry&unCurry函数
unCurry函数与curry函数区别:
curry化函数:固定部分参数,返回一个接受剩余参数的新函数,目的是为了缩小适用范围,创建一个针对性更强的函数。
unCurry化函数:扩大适用范围,创建一个应用范围更广的函数。使本来只有特定对象才适用的方法,扩展到更多的对象。
unCurry函数 参考:https://www.cnblogs.com/pigtail/p/3450852.html https://juejin.im/post/5b561426518825195f499772#heading-7
方法一:
class Toast{ constructor(){ this.prompt='' } show(){ console.log(this.prompt); } } var temObj={prompt:'tem'} Toast.prototype.show.call(temObj) function unCurry(fn){ return function(context){ var args=Array.prototype.slice(1)||[]; fn.apply(context,args) } } var unCurryShow=unCurry(Toast.prototype.show); unCurryShow(temObj)
方法2 Function.prototype.unCurrying = function(){ var self = this; return function(){ return Function.prototype.call.apply(self, arguments); } //return this.call.bind(this); } // 使用 var objShow = Toast.prototype.show.unCurrying(); objShow(obj);
应用:
Function.prototype.unCurry=function(){ return this.call.bind(this) } var objPush=Array.prototype.push.unCurry(); var temObj={}; objPush(temObj,'a','b')
var toUpperCase = String.prototype.toUpperCase.unCurrying(); console.log(toUpperCase('avd')); // AVD function AryUpper(ary) { return ary.map(toUpperCase); } console.log(AryUpper(['a', 'b', 'c'])); // ["A", "B", "C"]
var call = Function.prototype.call.unCurrying(); function $(id) { return this.getElementById(id); } var demo = call($, document, 'demo'); console.log(demo); //Function.prototype.call.call(fn,context,...args)
var objToString=Object.prototype.toString.unCurry() var fn1=function(){} objToString(objToString)
curry化 参考:https://juejin.im/post/5bf9bb7ff265da616916e816
function myCurry(fn){ if(fn.length<=1)return fn; let generator=function(...args){ return (args.length === fn.length?fn(...args):function(...arg){return generator(...args,...arg)}) }; return generator() }
参考:https://juejin.im/post/5cef46226fb9a07eaf2b7516#heading-11
带占位符的curry function curry(fn){ let placeHolder='_'; if(fn.length<=1)return fn function generator(oldArgs=[],newArgs){ oldArgs.forEach((item,ind,arr)=>{ if(item==placeHolder){ let spliceIndx=newArgs.findIndex(newArg=>newArg!==placeHolder) arr[ind]=newArgs.splice(spliceIndx,1)[0] } }) Array.prototype.push.apply(oldArgs,newArgs) let realArgs=oldArgs.filter(item=>item!==placeHolder); if(realArgs.length===fn.length){ return fn(...realArgs) }else if(realArgs.length===fn.length){ throw new Error('超出初始函数参数最大值') }else{ return (...newArgs)=>{return generator(oldArgs,newArgs)} } } return generator() }
function arr(a,b,c,d){
return [a,b,c,d]
}