Skip to content

Instantly share code, notes, and snippets.

@atticoos
Last active January 10, 2017 02:55
Show Gist options
  • Save atticoos/42c809dfd291a2c379647a6d96318be2 to your computer and use it in GitHub Desktop.
Save atticoos/42c809dfd291a2c379647a6d96318be2 to your computer and use it in GitHub Desktop.
const todoStore = new Store([]);
const add = newTodo => todos => todos.concat(newTodo);
const remove = oldTodo => todos => todos.filter(todo => todo !== oldTodo);
todoStore.subscribe(state => {
// rerender a UI with new state
console.log('next state', state);
})
todoStore.transition(add('hello')) // ['hello']
todoStore.transition(add('world')) // ['hello', 'world']
todoStore.transition(remove('hello')) // ['world']
/**
* State Container
*
* A state container is a stateful store that manages the state of a given subject.
* The store is purely functional, exposing a method `transitionState` that
* accepts a function, that when called with the current state, calculates the
* next state as its return value. This becomes the next state of the store.
*
* When the state changes, observers are notified with the next and last states.
* Observers have an opportunity to perform UI updates.
*
* Example Usage:
*
* const store = new Store([]);
*
* const add = input => lastState => lastState.concat(input);
* const remove = input => lastState => lastState.filter(i => i !== input);
*
* store.subscribe(state => console.log('next state': state))
*
* store.transition(add('hello')); // next state: ['hello']
* store.transition(add('world')); // next state: ['hello', world']
* store.transition(remove('hello)); // next state: ['world']
*
*
*/
function Store (initialState) {
var state = initialState;
var observers = [];
function transitionState (transitionFunction) {
var lastState = state;
var nextState = transitionFunction(state);
if (nextState !== lastState) {
state = nextState;
observers.forEach(observer => observer(nextState, lastState));
}
return state;
}
function subscribe (observer) {
// subscribed
observers.push(observer);
// unsubscribe
return () => observers = observers.filter(o => o !== observer);
}
function getState () {
return state;
}
return {
transition: transitionState,
subscribe: subscribe,
getState: getState
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment