函数式编程

122 阅读1分钟
  • 根据add函数,实现异步加法, asyncAdd(1,2,3,4,5)
 function add(a, b, callback) {
      callback(a + b)
    }
async function asyncAdd(...args) {
  if (args.length > 1) {
    const res = await new Promise(resolve => {
      add(args[0], args[1], sum => {
        resolve(sum)
      })
    })
    return asyncAdd(res, ...args.splice(2))
  } else {
    return args[0]
  }
}
asyncAdd(1, 2, 3, 4, 5).then(res => {
  console.log(res) // 15
})
  • 实现add函数柯里化, add(1,2)(3,4)(5) // 15
function add(){
  let args = [...arguments]
  const ret = function(){
    args = [...args, ...arguments]
    return ret
  }
  ret.toString = function(){
    return args.reduce((a, b)=>a+b)
  }
  return ret
}
  • 实现compose函数, compose(fn1, fn2, fn3)() => fn1(fn2(fn3()))
function fn1(x = 0){
  return x+1
}
function fn2(x = 0){
  return x+2
}
function fn3(x = 0){
  return x+3
}

function compose(...args){
  const ret = function (){
  let res
    for(let i=args.length -1;i>=0;i--){
      if(i === args.length -1){
        res = args[i]()
      }else{
        res = args[i](res)
      }
    }
    return res
  }
  return ret
}
  • 缓存函数 menery(fn)
function memery(fn){
  const map = new Map()
  const ret = function(...args){
    if(map.has(args[0])){
      console.log('from memery...')
      return map.get(args[0])
    }else{
     console.log('from calculate...')
      map.set(args[0], fn(args[0]))
      return fn(args[0])
    }
  }
  
  return ret
}

function add(n){
  return n * n
}