Skip to content

Commit

Permalink
Replace class with a factory function
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Jul 19, 2015
1 parent 2b4d416 commit 0623cf4
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 66 deletions.
57 changes: 0 additions & 57 deletions src/Store.js

This file was deleted.

64 changes: 57 additions & 7 deletions src/createStore.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,63 @@
import Store from './Store';
import invariant from 'invariant';
import isPlainObject from './utils/isPlainObject';

// Don't ever try to handle these action types in your code. They are private.
// For any unknown actions, you must return the current state.
// If the current state is undefined, you must return the initial state.
export const ActionTypes = {
INIT: '@@redux/INIT'
};

export default function createStore(reducer, initialState) {
const store = new Store(reducer, initialState);
invariant(
typeof reducer === 'function',
'Expected the reducer to be a function.'
);

let currentReducer = null;
let currentState = initialState;
let listeners = [];

function getState() {
return currentState;
}

function subscribe(listener) {
listeners.push(listener);

return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}

function dispatch(action) {
invariant(
isPlainObject(action),
'Actions must be plain objects. Use custom middleware for async actions.'
);

currentState = currentReducer(currentState, action);
listeners.forEach(listener => listener());
return action;
}

function getReducer() {
return currentReducer;
}

function replaceReducer(nextReducer) {
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}

replaceReducer(reducer);

return {
dispatch: ::store.dispatch,
subscribe: ::store.subscribe,
getState: ::store.getState,
getReducer: ::store.getReducer,
replaceReducer: ::store.replaceReducer
dispatch,
subscribe,
getState,
getReducer,
replaceReducer
};
}
2 changes: 1 addition & 1 deletion src/utils/combineReducers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mapValues from '../utils/mapValues';
import pick from '../utils/pick';
import invariant from 'invariant';
import { ActionTypes } from '../Store';
import { ActionTypes } from '../createStore';

function getErrorMessage(key, action) {
const actionType = action && action.type;
Expand Down
2 changes: 1 addition & 1 deletion test/utils/combineReducers.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import expect from 'expect';
import { combineReducers } from '../../src';
import { ActionTypes } from '../../src/Store';
import { ActionTypes } from '../../src/createStore';

describe('Utils', () => {
describe('combineReducers', () => {
Expand Down

0 comments on commit 0623cf4

Please sign in to comment.