• js 柯里化、深拷贝、浅拷贝


    curry

    const sum = (a, b, c, d) => a + b + c + d
    const curry = fn =>
      (judge = (...args) =>
        args.length >= fn.length ? fn(...args) : (...arg) => judge(...args, ...arg))
    const currySum = curry(sum)
    console.log(currySum(1, 2)(4)(3)) //10
    

    deepClone

    function getType(obj) {
      const str = Reflect.toString.call(obj)
      const map = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object',
        '[object Map]': 'map',
        '[object Set]': 'set',
      }
      if (obj instanceof Element) {
        // 判断是否是dom元素,如div等
        return 'element'
      }
      return map[str]
    }
    
    function deepClone(ori) {
      const type = getType(ori)
      let copy
      switch (type) {
        case 'array':
          return copyArray(ori, copy)
        case 'object':
          return copyObject(ori, copy)
        case 'function':
          return copyFunction(ori)
        case 'map':
          return copyMap(ori, copy)
        case 'set':
          return copySet(ori, copy)
        default:
          return ori
      }
    }
    
    function copyArray(ori, copy = []) {
      for (const [index, value] of ori.entries()) {
        copy[index] = deepClone(value)
      }
      return copy
    }
    
    function copyObject(ori, copy = {}) {
      for (const [key, value] of Reflect.entries(ori)) {
        copy[key] = deepClone(value)
      }
      return copy
    }
    
    function copyMap(ori, copy = new Map()) {
      for (const [key, value] of ori) {
        copy.set(deepClone(value))
      }
      return copy
    }
    
    function copySet(ori, copy = new Set()) {
      for (const [key, value] of ori.entries()) {
        copy.add(key, deepClone(value))
      }
      return copy
    }
    
    function copyFunction(ori) {
      const fun = eval(ori.toString())
      fun.prototype = ori.prototype
      return fun
    }
    
    

    shallowClone

    function shallowClone(ori) {
      if (typeof ori === 'object' && ori !== null) {
        return Array.isArray(ori) ? copyArray(ori) : copyObject(ori)
      }
      return ori
    }
    function copyObject(ori, copy = {}) {
      for (const [k, v] of Reflect.entries(ori)) {
        copy[k] = v
      }
      return copy
    }
    function copyArray(ori, copy = []) {
      for (const [k, v] of ori.entries()) {
        copy[k] = v
      }
      return copy
    }
    
    
  • 相关阅读:
    刚好遇见你——软件工程
    int main(int argc,char* argv[]) 简单理解
    奇偶数分离
    A+B Problem
    日期计算
    正三角形的外接圆面积
    数数小木块
    谁是最好的Coder
    水仙花数
    5个数求最值
  • 原文地址:https://www.cnblogs.com/smzd/p/11912827.html
Copyright © 2020-2023  润新知