美文网首页
javascript高阶特性

javascript高阶特性

作者: halowyn | 来源:发表于2021-03-06 21:15 被阅读0次
      1. javascript高阶特性之-curry化(柯里化)
    function multiplyBy (num1) {
      return function (num2) {
        return num1 * num2
      }
    }
    const multiplyByThree = multiplyBy(3)
    const multiplyByFive = multiplyBy(5)
    console.log(multiplyByThree(4))
    console.log(multiplyByFive(6))
    
    // 参数curry化
    function add2 (...args) {
      return args.reduce((total, currentVal) => {
        total += currentVal
        return total
      }, 0)
    }
    function curry (fn) {
      let allArgs = []
      return function reFn (...args) {
        if (args.length === 0) {
          return fn.apply(this, allArgs)
        } else {
          allArgs = allArgs.concat(args)
          return reFn
        }
      }
    }
    const curryAdd2 = curry(add2)
    console.log(curryAdd2(1)(2)(3)(4,5)())
    
    1. javascript高阶特性-串行执行promises
    // 串行执行promise
    function runPromiseInSequence (arr, input) {
      return arr.reduce(
        (promiseChain, currentFunction) => promiseChain.then(currentFunction),
        Promise.resolve(input)
      )
    }
    
    function p1 (a) {
      return new Promise((resolve, reject) => {
        resolve(a * 5)
      })
    }
    function p2 (a) {
      return new Promise((resolve, reject) => {
        resolve(a * 2)
      })
    }
    function p3 (a) {
      return new Promise((resolve, reject) => {
        resolve(a * 3)
      })
    }
    function p4 (a) {
      return new Promise((resolve, reject) => {
        resolve(a * 4)
      })
    }
     
    const promiseArr = [p1, p2, p3, p4]
    runPromiseInSequence(promiseArr, 10).then(console.log)
    
    1. javascript高阶特性-递归fib
    function fib (n) {
    if (n < 3) return 1
    return fib(n - 2) + fib(n - 1)
    }
    console.log(fib(6))
    console.log(fib(10))
    
    //循环
    function fib2 (n) {
    let first = 1, second = 1
    while (n --> 2) {
      [first, second] = [second, first + second]
    }
    return second
    }
    console.log(fib(6))
    console.log(fib(10))
    
    // 尾调用优化
    function fibTail (n, first = 1, second = 1) {
    if (n < 3) return second
    return fibTail(n - 1, second, (first + second))
    }
    console.log(fib(6))
    console.log(fib(10))
    
    1. javascript高阶特性-递归扁平化数组
    // javascript高阶特性-递归扁平化数组
    function flat(arr) {
      let result = []
      (function innerFlat(arr) {
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          if (Array.isArray(element)) {
            innerFlat(element)
          } else {
            result.push(element)
          }
        }
      })(arr)
      return result
    }
    console.log(flat([1, 2]))
    
    function flatWhile(arr) {
      let result = []
      while (arr.some(item => Array.isArray(item))) {
        result = [].concat(...arr)
      }
      return result
    }
    console.log(flatWhile(flat([1, [2, 3], [4. [5, 6]]])))
    
    1. 数组和属性结构的互相转换
    2. 高阶函数:函数可以作为参数输入也可以作为返回输出
    3. 函数缓存
    function memo (fn) {
    if (typeof fn !== 'function') {
      console.error('argument of fn must be a function')
    }
    const cache = {}
    return function (...args) {
      const argsStr = args.join('').toString()
      if (cache[argsStr]) {
        console.log('from cache')
        return cache[argsStr]
      } else {
        console.log('from fn')
        return cache[argsStr] = fn.apply(this, args)
      }
    }
    }
    function add (a, b, c) {
    return a + b + c
    }
    
    const memoAdd = memo(add)
    console.log(memoAdd(1, 2, 3))
    console.log(memoAdd(1, 2, 3))
    console.log(memoAdd(1, 2, 5))
    
    1. compose函数作用:前一个函数的执行结果作为下一个函数的输入参数
      入参:函数集合
    function compose (...fns) {
      return (...args) => {
        return fns.reduce((arg, currentFn) => {
          return currentFn.apply(this, Array.isArray(arg) ? arg : [arg])
        }, args)
      }
    }
    function fn1 (...args) {
      return args.reduce((total, current) => {
        total += current
        return total
      })
    }
    function fn2(arg) {
      return 2 * arg
    }
    function fn3(arg) {
      return arg + 'aaa'
    }
    const res = compose(fn1, fn2, fn3)(1, 2, 3)
    console.log(res)
    
    1. 异步compose函数
    function createAsyncFn(delay) {
      return function (...lastResult) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            const res = lastResult.reduce((total, val) => {
              total += val
              return total
            })
            resolve(res)
          }, delay)
        })
      }
    }
    
    const asyncFn1 = createAsyncFn(1000)
    const asyncFn2 = createAsyncFn(1000)
    const asyncFn3 = createAsyncFn(1000)
    const asyncFn4 = function (...lastResult) {
      return new Promise((resolve, reject) => {
        setTimeout(function() {
          const res = lastResult.join('') + '_asyncFn4'
          resolve(res)
        }, 1000)
        // resolve(lastResult.join('') + '_asyncFn5')
      })
    }
    const asyncFn5 = function (...lastResult) {
      return new Promise(function(resolve, reject) {
        resolve(lastResult.join('') + '_asyncFn5')
      })
    }
    
    function asyncCompose(...asyncFns) {
      return function (...args) {
        return asyncFns.reduce((prev, next) => {
          return prev.then(function(lastResult){
            return next.apply(null, Array.isArray(lastResult) ? lastResult : [lastResult])
          })
        }, Promise.resolve(args))
      }
    }
    const asyncRes = asyncCompose(asyncFn1, asyncFn2, asyncFn3, asyncFn4, asyncFn5)(1, 2, 3)
    asyncRes.then(res => {
      console.log('final result:' + res)
    })
    
    1. 惰性求值 lazy evaluate

    相关文章

      网友评论

          本文标题:javascript高阶特性

          本文链接:https://www.haomeiwen.com/subject/nbhsqltx.html