Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created September 4, 2016 02:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bouzuya/05d967cf47aa5cee69d1c8df83a32ca1 to your computer and use it in GitHub Desktop.
Save bouzuya/05d967cf47aa5cee69d1c8df83a32ca1 to your computer and use it in GitHub Desktop.
Raynos/weakmap-shim create-store.ts
// 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