柯里化和Proxy代理案例实现
实现add(1)(2)(3),柯里化
主要有3个作用: 参数复用、提前返回和 延迟执行
考点:函数柯里化 函数柯里化概念:柯里化(currying)是把接受多个参数
的函数转变为接受一个单一参数的函数,并且返回接受余下参数且返回结果的新的函数技术
// 1.粗暴版 function add(a) { return function (b) { return function (c) { return a + b + c; } } } console.log(add(1)(2)(3));
//2) 柯里化解决方案 // 参数长度固定 const curry = (fn) => (juedge = (...args) => args.length === fn.length ? fn(...args) : (...arg) => judge(...args, ...arg)); const add=(a,b,c)=>a+b+c; const curryAdd=curry(add); console.log(curryAdd(1)(2)(3)) var add = function (m) { var temp = function (n) { return add(m + n); } temp.toString = function () { return m; } return temp; }; console.log(add(3)(4)(5)); // 12 console.log(add(3)(6)(9)(25)); // 43
// 利用了函数的柯里化和闭包特性 function add(...arg) { let a = [...arg]; _add = function (...innerArg) { if (innerArg.length === 0) { return a.reduce(function (a, b) { return a + b }) } else { console.log(innerArg); [].push.apply(a, innerArg) return _add; } } return _add } console.log(add(1)(2,2,3)()) // 6
手写一个ES6proxy如何实现arr[-1]的访问
const negativeArray = els => { return new Proxy(els, { get: (target, propKey, receiver) => { //如果等于小于0数组就从后1取第一个数 let prop = +propKey < 0 ? String(target.length + +propKey) : propKey console.log(prop, propKey); return Reflect.get(target, prop, receiver) } }) } const unicorn = negativeArray(['1aaa1', 'aa', 'bb', 'ccc']); console.log(unicorn[-5])

浙公网安备 33010602011771号