Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. // alternative for globally reusable variables
  2.  
  3. // supports contexts
  4. // can store all javascript types
  5.  
  6. // to create object-based unique contexts,
  7. // we advise assigning a uuidv4 to that object
  8. // then using that uuid as the context for that object.
  9.  
  10. // best use cases:
  11. // - when you're using chained promises
  12. // instead of cluttering your args & chains w/ variables
  13. // use keystore contexts instead;
  14. // makes your code cleaner & your promises more reusable.
  15.  
  16. class KeyStore{
  17. constructor(){
  18. console.log("Yay KeyStore!");
  19. this.storage = {};
  20. this.contexts = {};
  21. }
  22. set(_key, _value){
  23. this.storage[_key] = _value;
  24. }
  25. get(_key){
  26. return this.storage[_key];
  27. }
  28. pullContext(_context){
  29. if(this.contexts[_context]){
  30. return this.contexts[_context];
  31. }else{
  32. this.contexts[_context] = {
  33. storage: {},
  34. set: function(_key, _value){
  35. this.storage[_key] = _value;
  36. return this;
  37. },
  38. get: function(_key){
  39. return this.storage[_key];
  40. }
  41. };
  42. return this.contexts[_context];
  43. }
  44. }
  45. clearContext(_context){
  46. this.contexts[_context] = null;
  47. return true;
  48. }
  49. }
  50.  
  51. // usage
  52.  
  53. let _KeyStore = new KeyStore();
  54.  
  55. _KeyStore.set("yeah", "lol");
  56.  
  57. console.log(_KeyStore.get("yeah"));
  58. // lol
  59.  
  60. console.log(_KeyStore.pullContext("a").set("b", 2).get("b"));
  61. // 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement