From 25bc16ea27ab72d827c3b5ede7b552936de7efaa Mon Sep 17 00:00:00 2001 From: YangJ0605 <1442122744@qq.com> Date: Tue, 19 May 2020 10:56:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=AF=8F=E6=97=A5=E5=AD=A6=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- deepclone.js | 38 +++++++++++++++++++++++++++++++ promise.js | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 deepclone.js create mode 100644 promise.js diff --git a/deepclone.js b/deepclone.js new file mode 100644 index 0000000..7fbde95 --- /dev/null +++ b/deepclone.js @@ -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 + } +} \ No newline at end of file diff --git a/promise.js b/promise.js new file mode 100644 index 0000000..6fbbd5b --- /dev/null +++ b/promise.js @@ -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) +}) \ No newline at end of file