Skip to content

Instantly share code, notes, and snippets.

@selfsame
Last active May 24, 2018 18:43
Show Gist options
  • Save selfsame/14ed691e83056997e8acc009c4154335 to your computer and use it in GitHub Desktop.
Save selfsame/14ed691e83056997e8acc009c4154335 to your computer and use it in GitHub Desktop.
generic react-redux store actions
import { createStore } from "redux"
const deepcopy = (col) => {
return JSON.parse(JSON.stringify(col))}
const shallowcopy = (col) => {
return Array.isArray(col)?[...col]:{...col}}
const update = (col, k, f) => {
col = shallowcopy(col)
col[k] = f(col[k])
return col}
const update_in = (col, path, f) => {
var o = deepcopy(col)
col = o
for (var i = 0; i < path.length; i++) {
var k = path[i]
if (i === path.length - 1) {
col[k] = f(col[k])
} else {
if (col[k] === undefined) {
col[k] = isNaN(path[i+1])?{}:[]}
col = col[k]}}
return o}
const assoc = (col, k, v) => {
return update(col, k, (_)=>v)}
const assoc_in = (col, path, v) => {
return update_in(col, path, (_)=>v)}
const action = (type, payload) => ({type:type, payload:payload})
const initialState = {}
const Reducer = (state = initialState, action) => {
switch (action.type) {
case 'ASSOC' : return assoc(state, action.payload.k, action.payload.v)
case 'ASSOC_IN' : return assoc_in(state, action.payload.path, action.payload.v)
case 'UPDATE': return update(state, action.payload.k, action.payload.f)
case 'UPDATE_IN': return update_in(state, action.payload.path, action.payload.f)
default: return state}}
const store = createStore(Reducer)
const ASSOC = (k, v) => store.dispatch(action('ASSOC', {k:k, v:v}))
const ASSOC_IN = (path, v) => store.dispatch(action('ASSOC_IN', {path:path, v:v}))
const UPDATE = (k, f) => store.dispatch(action('UPDATE', {k:k, f:f}))
const UPDATE_IN = (path, f) => store.dispatch(action('UPDATE_IN', {path:path, f:f}))
export {store, assoc, assoc_in, update, update_in, ASSOC, ASSOC_IN, UPDATE, UPDATE_IN}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment