Skip to content

Commit

Permalink
每日学习
Browse files Browse the repository at this point in the history
  • Loading branch information
abstain23 committed May 19, 2020
1 parent 5a6777d commit 25bc16e
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
38 changes: 38 additions & 0 deletions deepclone.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
function _type(value) {
return Object.toString.call(value).slice(8,-1).toLocaleLowerCase()
}

function deepclone(obj) {
if(obj === null) return null
if(typeof obj !== 'object') return obj
if(_type(obj) === 'regexp') return new RegExp(obj)
if(_type(obj) === 'date') return new Date(obj)
const newObj = new obj.constructor
for(const key in obj) {
if(obj.hasOwnProperty(key)) {
let item = obj[key]
newObj[key] = deepclone(item)
}
}
return newObj
}

function deepclone2(obj) {
if(typeof obj !== 'object' || obj === null) return
let newObj = new obj.constructor
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
let item = obj[key],itemType = _type(item)
if(item !== null && typeof item === 'object') {
if(/(regexp|date)/.test(itemType)) {
newObj[key] = new item.constructor(item)
continue
}
newObj[key] = deepclone2(item)
continue
}
newObj[key] = item
}
return newObj
}
}
63 changes: 63 additions & 0 deletions promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

class MyPromise {
constructor(fn) {
this.state = PENDING
//终值
this.value = null
//拒因
this.reason = null
//成功回调队列
this.onResolvedCbs = []
//拒绝回调队列
this.onRejectedCbs = []

const resolve = value => {
setTimeout(() => {
if(this.state === PENDING) {
this.state = RESOLVED
this.value = value
this.onResolvedCbs.map(cb => {
this.value = cb(this.value)
})
}
})
}

const reject = reson => {
setTimeout(() => {
if(this.state === PENDING) {
this.state = REJECTED
this.reason = reson
this.onRejectedCbs.map(cb => {
this.reason = cb(this.reason)
})
}
})
}
try {
fn(resolve, reject)
} catch(e) {
reject(e)
}
}

then(onResolved, onRejected) {
typeof onResolved === 'function' && this.onResolvedCbs.push(onResolved)
typeof onRejected === 'function' && this.onRejectedCbs.push(onRejected)
return this
}
}

new MyPromise((resolve,reject) => {
setTimeout(() => {
resolve(2)
},1000)
}).then(res => {
console.log(res)
return res + 1
}).then(res => {
console.log(res)
})

0 comments on commit 25bc16e

Please sign in to comment.