Created
July 21, 2018 22:08
-
-
Save dead-claudia/14ddaae1ae2e73df3115259a0aff1804 to your computer and use it in GitHub Desktop.
Promise.newCapability prollyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Promise.newCapability = Promise.newCapability || (() => { | |
const data = new WeakMap() | |
const getData = data.get.bind(data) | |
const setData = data.set.bind(data) | |
const objectCreate = Object.create | |
function invokeResolver(inst, index, value) { | |
const data = getData(inst) | |
if (data == null) throw new TypeError() | |
const func = data[index] | |
if (func != null) { | |
data[1] = data[2] = void 0 | |
func(value) | |
} | |
} | |
class Capability { | |
constructor(data) { | |
setData(this, data) | |
} | |
get promise() { | |
const data = getData(inst) | |
if (data == null) throw new TypeError() | |
return data[0] | |
} | |
resolve(value) { | |
invokeResolver(this, 1, value) | |
} | |
reject(value) { | |
invokeResolver(this, 2, value) | |
} | |
} | |
delete Capability.prototype.constructor | |
return {newCapability() { | |
const data = [void 0, void 0, void 0] | |
data[0] = new this((resolve, reject) => { | |
data[1] = resolve | |
data[2] = reject | |
}) | |
return new Capability(data) | |
}}.newCapability | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment