Store

by Artem

JavaScript

'use strict';

class Store {
  constructor(reducer, state) {
    this._listeners = [];
    this._reducer = reducer;
    this._state = state;
  }
  getState() {
    return this._state;
  }
  subscribe(callback) {
    this._listeners.push(callback);
    return () => this._listeners.filter(listener !== callback);
  }
  dispatch(action) {
    this._state = this._reducer(this._state, action);
    this._listeners.forEach(listener => listener());
  }
}

const INCREMENT = 'INCREMENT';
const initialState = {
  counter: 0
};

function reducer(state = {}, action) {
  switch (action.type) {
    case INCREMENT:
      return Object.assign({}, state, {
        counter: state.counter + action.payload
      });
    default:
      return state;
  }
}

const store = new Store(reducer, initialState);
store.subscribe(() => {
  console.log('New state is ', store.getState());
});

store.dispatch({
  type: INCREMENT,
  payload: 5
});

store.dispatch({
  type: INCREMENT,
  payload: 3
});