Created
September 4, 2016 02:18
-
-
Save bouzuya/05d967cf47aa5cee69d1c8df83a32ca1 to your computer and use it in GitHub Desktop.
Raynos/weakmap-shim create-store.ts
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
// Original: https://github.com/Raynos/weakmap-shim create-store | |
type StoreId = Object; | |
type Store = (obj: Object) => Object; | |
type Item = { _storeId: StoreId; valueOf: ItemValueOf; }; | |
type ItemValueOf = (storeId?: StoreId) => Object | Item; | |
const createStore = (): Store => { | |
const storeId: StoreId = {}; | |
return (obj: Object | Item): Item => { | |
const objOrItem = (<ItemValueOf>obj.valueOf)(storeId); | |
return isItem(objOrItem, storeId) | |
? objOrItem | |
: createItem(objOrItem, storeId); | |
}; | |
}; | |
const createItem = (obj: Object, storeId: StoreId): Item => { | |
const item = { _storeId: storeId }; | |
const originalValueOf = obj.valueOf; | |
Object.defineProperty(obj, 'valueOf', { | |
value(s?: StoreId) { | |
return s === storeId ? item : originalValueOf.apply(this, arguments); | |
}, | |
writable: true | |
}); | |
return item; | |
}; | |
const isItem = ( | |
objOrItem: Object | Item, storeId: StoreId | |
): objOrItem is Item => { | |
return (<Item>objOrItem)._storeId === storeId; | |
}; | |
export { createStore }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment