Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. const clone = o => JSON.parse(JSON.stringify(o));
  2.  
  3. const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;
  4.  
  5. const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b)
  6.  
  7. class PubSub {
  8.  
  9. #callbackList
  10.  
  11. constructor() {
  12. this.#callbackList = [];
  13. }
  14.  
  15. publish(currentState, nextState) {
  16. if (!isObject(currentState)) throw new Error('currentState should be and object');
  17. if (!isObject(nextState)) throw new Error('nextState should be and object');
  18. this.callbackList.forEach(item => {
  19. const currentValue = item.config(currentState);
  20. const nextValue = item.config(nextState);
  21. if (!isEqual(currentValue, nextValue)) {
  22. item.callback(nextValue);
  23. }
  24. });
  25. }
  26.  
  27. subscribe(callback, config) {
  28. if (typeof callback !== 'function')
  29. throw new Error('callback should be a function');
  30. if (typeof config !== 'function')
  31. throw new Error('config should be a function');
  32. this.#callbackList = [
  33. ...this.#callbackList,
  34. { callback, config }
  35. ];
  36. return true;
  37. }
  38. }
  39.  
  40. class Store {
  41.  
  42. #internalState
  43. #pubsub
  44.  
  45. constructor(initialState = {}) {
  46. if (!isObject(initialState)) throw new Error('initial state must be a object');
  47. this.#internalState = clone(initialState);
  48. this.#pubsub = new Pubsub()
  49. }
  50.  
  51. get state() {
  52. return clone(this.#internalState);
  53. }
  54.  
  55. set state(value) {
  56. return false;
  57. }
  58.  
  59. setState(value) {
  60. if (!isObject(value)) throw new Error('value must be a object');
  61. const currentState = clone(this.#internalState);
  62. const nextState = Object.assign(clone(currentState), clone(value))
  63. this.#internalState = nextState
  64. this.#pubsub.publish(currentState, nextState)
  65. return nextState;
  66. }
  67.  
  68. subscribe(callback, config) {
  69. return this.#pubsub.subscribe(callback, config)
  70. }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement