Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. function createStore(reducer, initState, enhancer) {
  2. if (typeof initState == "function" && enhancer == null) {
  3. enhancer = initState;
  4. initState = undefined;
  5. }
  6.  
  7. if (enhancer !== undefined) {
  8. return enhancer(createStore)(reducer, initState);
  9. }
  10.  
  11. let currentReducer = reducer;
  12. let currentState = initState;
  13. let currentListeners = [];
  14. let nextListeners = currentListeners;
  15.  
  16. function dispatch(action) {
  17. currentState = currentReducer(currentState, action);
  18.  
  19. if (currentListeners !== nextListeners) {
  20. currentListeners = nextListeners;
  21. }
  22. for (let i = 0; i < currentListeners.length; i++) {
  23. const fn = currentListeners[i];
  24. fn();
  25. }
  26. }
  27.  
  28. function replaceReducer(nextReducer) {
  29. currentReducer = nextReducer;
  30. }
  31.  
  32. function subscribe(callback) {
  33. if (nextListeners === currentListeners) {
  34. nextListeners = currentListeners.slice();
  35. }
  36. nextListeners.push(callback);
  37. return function unsubscribe() {
  38. if (nextListeners === currentListeners) {
  39. nextListeners = currentListeners.slice();
  40. }
  41. if (nextListeners.indexOf(callback) > -1) {
  42. nextListeners.splice(nextListeners.indexOf(callback), 1);
  43. }
  44. };
  45. }
  46.  
  47. function getState() {
  48. return currentState;
  49. }
  50.  
  51. let store = {
  52. subscribe,
  53. getState,
  54. dispatch,
  55. replaceReducer
  56. };
  57.  
  58. store.dispatch({
  59. type: "INIT"
  60. });
  61.  
  62. return store;
  63. }
  64.  
  65. function applyMiddleware(...middlewares) {
  66. return createStore => (...args) => {
  67. const store = createStore(...args);
  68. let dispatch;
  69.  
  70. const middlewareAPI = {
  71. getState: store.getState,
  72. dispatch: (...args) => dispatch(...args)
  73. };
  74.  
  75. const chain = middlewares.map(middleware => middleware(middlewareAPI));
  76.  
  77. dispatch = compose(...chain)(store.dispatch);
  78.  
  79. return {
  80. ...store,
  81. dispatch
  82. };
  83. };
  84. }
  85.  
  86. function compose(...fns) {
  87. if (fns.length === 0) {
  88. return arg => arg;
  89. }
  90. if (fns.length === 1) {
  91. return fns[0];
  92. }
  93. return fns.reduce((a, b) => (...args) => a(b(...args)));
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement