store.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Modes } from './../mode';
  2. export class Store {
  3. constructor () {
  4. this.store = {};
  5. this.nextStore = null;
  6. this.mode = Modes.RUN;
  7. }
  8. cloneStore () {
  9. return Object.assign(new Store(), this);
  10. }
  11. extendStore (nextStore) {
  12. this.nextStore = nextStore;
  13. }
  14. applyStore (id) {
  15. if(!this.store[id]) {
  16. if (this.nextStore === null) {
  17. // TODO: better error message
  18. throw new Error(`Variable ${id} is not defined.`);
  19. } else {
  20. return this.nextStore.applyStore(id);
  21. }
  22. }
  23. return this.store[id];
  24. }
  25. isDefined (id) {
  26. if(!this.store[id]) {
  27. if (this.nextStore === null) {
  28. return false;
  29. } else {
  30. return this.nextStore.isDefined(id);
  31. }
  32. }
  33. return true;
  34. }
  35. updateStore (id, storeObj) {
  36. if(!this.store[id]) {
  37. if (this.nextStore !== null) {
  38. this.nextStore.updateStore(id, storeObj);
  39. } else {
  40. throw new Error(`Variable ${id} is not defined.`);
  41. }
  42. } else {
  43. const old = this.applyStore(id);
  44. if (!old.isCompatible(storeObj)) {
  45. // TODO: better error message
  46. throw new Error(`${storeObj.value} is not compatible with ${id} of type ${old.type}`);
  47. } else if (old.readOnly) {
  48. // TODO: better error message
  49. throw new Error(`Cannot change value, ${id} is read-only`);
  50. } else {
  51. this.store[id] = Object.freeze(storeObj);
  52. }
  53. }
  54. }
  55. insertStore (id, storeObj) {
  56. if(this.store(id)) {
  57. // TODO: Better error message
  58. throw new Error(`Variable ${id} is already defined.`);
  59. } else {
  60. this.store[id] = Object.freeze(storeObj)
  61. }
  62. }
  63. }