每日一练:promise deepclone

const PENDING = "PENDING"
const FULFILLED = "FULFILLED"
const REJECTED = "REJECTED"

const resolvedPromise = (promise, x, resolve, reject) => {
  if (promise === x) {
    reject(new TypeError("TypeError"))
  }

  if ((typeof x === "object" && x !== null) || typeof x === "function") {
    let called = false
    try {
      const then = x.then
      if (typeof then === "function") {
        then.call(x, y => {
          if (called) return
          called = true
          resolvedPromise(promise, y, resolve, reject)
        }, r => {
          if (called) return
          called = true
          reject(r)
        })
      } else {
        resolve(x)
      }
    } catch (e) {
      if (called) return
      called = true
      reject(e)
    }
  } else {
    resolve(x)
  }
}

class Promise {
  constructor(executor) {
    this.status = PENDING
    this.value = undefined
    this.reason = undefined
    this.onResolvedCallbacks = []
    this.onRejectedCallbacks = []

    const resolve = value => {
      if (this.status === "PENDING") {
        this.status = FULFILLED
        this.value = value
        this.onResolvedCallbacks.forEach(fn => fn())
      }
    }

    const reject = reason => {
      if (this.status === PENDING) {
        this.status = REJECTED
        this.reason = reason
        this.onRejectedCallbacks.forEach(fn => fn())
      }
    }

    executor(resolve, reject)
  }

  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === "function" ? onFulfilled : val => val
    onRejected = typeof onRejected === "function" ? onRejected : err => {throw err}
    const promise2 = new Promise((resolve, reject) => {
        if (this.status === FULFILLED) {
          setTimeout(() => {
            try {
              let x = onFulfilled(this.value)
              resolvedPromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          })
        }

        if (this.status === REJECTED) {
          setTimeout(() => {
            try {
                let x = onRejected(this.reason)
                resolvedPromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          })
        }

        if (this.status === PENDING) {
          this.onResolvedCallbacks.push(() => {
            setTimeout(() => {
              try {
                let x = onFulfilled(this.value)
                resolvedPromise(promise2, x, resolve, reject)
              } catch (e) {
                reject(e)
              }
            })
          })

          this.onRejectedCallbacks.push(() => {
            setTimeout(() => {
              try {
                let x = onRejected(this.reason)
                resolvedPromise(promise2, x, resolve, reject)
              } catch (e) {
                reject(e)
              }
            })
          })
        }
    })

    return promise2
  }

  catch(errCallback) {
    return this.then(null, errCallback)
  }

  finally(fn) {
    return this.then(fn, fn)
  }

  static resolve() {
    return new Promise((resolve, reject) => {
      resolve(this.value)
    })
  }

  static reject() {
    return new Promise((resolve, reject) => {
      reject(this.reason)
    })
  }
}

const p = new Promise((resolve, reject) => {
  resolve("哈哈")
})

p.then(data => {
  console.log(data)
  return data
}).then(data => {
  console.log(data)
  throw new Error("好玩")
}).catch(err => {
  console.log(err)
  return "你猜"
}).finally(data => {
  console.log(data)
})


const deepClone = (originObject, hash = new WeakMap) => {
    if (originObject == null) return originObject
    if (typeof originObject !== "object") return originObject
    if (originObject instanceof RegExp) return new RegExp(originObject)
    if (originObject instanceof Date) return new Date(originObject)
    // ...

    const newInstance = originObject.constructor ? new originObject.constructor : Object.create(null);
    if (hash.has(originObject)) {
        return hash.get(originObject)
    }
    hash.set(originObject, newInstance)

    for (let key in originObject) {
        if (typeof originObject.hasOwnProperty === 'function' ) {
            if(originObject.hasOwnProperty(key)){
                newInstance[key] = deepClone(originObject[key], hash)
            }
        }else {
            newInstance[key] = deepClone(originObject[key], hash)
        }
    }
    return newInstance
}

const a = {
    name: "amin",
    age: 10,
    like: () => {console.log("play")},
    food: { fruit: ["apple", "banana", "watermelon"]}
}

const b = deepClone(a)
console.log(b)


{ name: 'am',
  age: 10,
  like: [Function: like],
  food: { fruit: [ 'apple', 'banana', 'watermelon' ] } }
  
哈哈
哈哈
Error: 好玩
你猜

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值