Last active
March 30, 2017 15:18
-
-
Save servercharlie/f5b104ceb0bb559e6281b040e6d875e4 to your computer and use it in GitHub Desktop.
KeyStore JS
This file contains hidden or 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
// alternative for globally reusable variables | |
// supports contexts | |
// can store all javascript types | |
// to create object-based unique contexts, | |
// we advise assigning a uuidv4 to that object | |
// then using that uuid as the context for that object. | |
// best use cases: | |
// - when you're using chained promises | |
// instead of cluttering your args & chains w/ variables | |
// use keystore contexts instead; | |
// makes your code cleaner & your promises more reusable. | |
class KeyStore{ | |
constructor(){ | |
console.log("Yay KeyStore!"); | |
this.storage = {}; | |
this.contexts = {}; | |
} | |
set(_key, _value){ | |
this.storage[_key] = _value; | |
} | |
get(_key){ | |
return this.storage[_key]; | |
} | |
pullContext(_context){ | |
if(this.contexts[_context]){ | |
return this.contexts[_context]; | |
}else{ | |
this.contexts[_context] = { | |
storage: {}, | |
set: function(_key, _value){ | |
this.storage[_key] = _value; | |
return this; | |
}, | |
get: function(_key){ | |
return this.storage[_key]; | |
} | |
}; | |
return this.contexts[_context]; | |
} | |
} | |
clearContext(_context){ | |
this.contexts[_context] = null; | |
return true; | |
} | |
} | |
// usage | |
let _KeyStore = new KeyStore(); | |
_KeyStore.set("yeah", "lol"); | |
console.log(_KeyStore.get("yeah")); | |
// lol | |
console.log(_KeyStore.pullContext("a").set("b", 2).get("b")); | |
// 2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment