store.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Modes } from './../modes';
  2. export class Store {
  3. constructor() {
  4. this.store = {};
  5. this.nextStore = null;
  6. this.mode = Modes.RUN;
  7. }
  8. extendStore (nextStore) {
  9. this.nextStore = nextStore;
  10. }
  11. applyStore (id) {
  12. if(!this.store[id]) {
  13. if (this.nextStore !== null) {
  14. return this.nextStore.applyStore(id);
  15. } else {
  16. // TODO: better error message
  17. throw new Error(`Variable ${id} not found.`);
  18. }
  19. }
  20. return this.store[id];
  21. }
  22. updateStore (id, stoObj) {
  23. if(!this.store[id]) {
  24. if(this.extendStore !== null) {
  25. return this.extendStore.updateStore(id, stoObj);
  26. } else {
  27. // TODO: better error message
  28. throw new Error(`Variable ${id} not found.`);
  29. }
  30. } else {
  31. const oldObj = this.applyStore(id);
  32. if(oldObj.readOnly) {
  33. // TODO: better error message
  34. throw new Error("Cannot change value of a read only variable: " + id);
  35. }
  36. if(oldObj.isCompatible(stoObj)) {
  37. this.store[id] = Object.freeze(stoObj);
  38. return this;
  39. } else {
  40. // TODO: better error message
  41. throw new Error(`${stoObj.type} is not compatible with the value given`);
  42. }
  43. }
  44. }
  45. insertStore (id, stoObj) {
  46. if (this.store[id]) {
  47. // TODO: better error message
  48. throw new Error(`${id} is already defined`);
  49. }
  50. this.store[id] = stoObj;
  51. return this;
  52. }
  53. }