Slice and compose redux-type reducers.

Herby Vojčík 60eaa50740 0.6.2 6 years ago
src a9fbd6f229 Add deget, decow; deprecate cowValueModel. 6 years ago
.gitignore de53914b31 Initial commit 7 years ago
LICENSE de53914b31 Initial commit 7 years ago
README.md a9fbd6f229 Add deget, decow; deprecate cowValueModel. 6 years ago
index.js eda0fa5507 Stop precompiling w/ babel. 7 years ago
package.json f1309b6393 0.6.2 6 years ago

README.md

redux-sac

Slice redux objects (reducers, middleware, ...)

subReducer(key, reducer, additionalKey, ...)

Creates a wrapper reducer that calls reducer on the sub-state specified by key. Key can go in different formats, see cowValueModel below. Rest of the state is left untouched.

const r = subReducer("persons", personReducer);
  
r({persons: ["John", "Jill"], cars: ["Honda"]}, action);
// => {
//   persons: personReducer(["John", "Jill"], action), 
//   cars: ["Honda"]
// }

Respects redux convention that if no change was made, the identical object should be returned. So in previous case, if personReducer would return the identical array, r would return the state object it was passed in.

If persons were deeper in hierarchy, it could have been created as const r = subReducer("files.persons", personReducer); for example.

You may pass additional keys as addition arguments. In that case, additional parts of state will be fetched and passed to a sub-reducer:

const r = subReducer("persons", personReducer, "assets.cars");
  
r({persons: ["John", "Jill"], assets: {cars: ["Honda"]}}, action);
// => {
//   persons: personReducer(["John", "Jill"], action, ["Honda"]), 
//   assets: {cars: ["Honda"]}
// }

This technique is mentioned in Redux docs, in "Beyond combineReducers" page.

subMiddleware(key | selectorFn, middleware)

Creates a wrapper middleware on the sub-state specified by key or the selector function selectorFn by decorating getState part of the passed arg. The key can have different format, see cowValueModel below. Rest of the passed arg is left untouched.

const r = subMiddleware("persons", ({getState}) => next => action => {
  console.log(JSON.stringify(getState()));
  return next(action);
});
  
const altR = subMiddleware(state => state.persons, ({getState}) => next => action => {
  console.log(JSON.stringify(getState()));
  return next(action);
});
  
// use r or altR in creation of store
  
store.getState();
// => {persons: ["John", "Jill"], cars: ["Honda"]}
store.dispatch({type: "any"});
// console => ["John","Jill"] 

If persons were deeper in hierarchy, it could have been created as const r = subMiddleware("files.persons", ...); for example.

You can use subMiddleware to sub-state anything getting one parameter in which one of the properties passed is getState function; it is not special-case for middleware. For example, it is usable for wrapping redux-effex effect function.

subEffex(key | selectorFn, effects)

Creates a wrapper around each element of the effects array on the sub-state specified by key or by selector function selectorFn by decorating effect function with subMiddleware and returns the array of the wrapped effects.

const effects = [{
  action: "foo",
  effect: ({getState}) => {
    console.log(JSON.stringify(getState()));
  }
}];
  
const e = subEffex("persons", effects);
const altE = subEffex(state => state.persons, effects);
  
// use e or altE in creation of store
  
store.getState();
// => {persons: ["John", "Jill"], cars: ["Honda"]}
store.dispatch({type: "foo"});
// console => ["John","Jill"] 

Compose

composeReducers(reducer1, reducer2, ...)

Creates a wrapper reducer that calls passed reducers one after another, passing intermediate states. and returning the result of the last one.

Useful to "concatenate" a few subReducers. like:

composeReducers(
  subReducer("files.persons", personReducer, "assets.swag"),
  subReducer("files.clients", clientReducer, "news"),
  subReducer("assets", assetReducer),
  baseReducer
)

Redux helpers

deepGetOrNil(key, ...)

deget(key, ...)

Creates an accessor function allowing to get specified key from any object.

Specify keys by passing a list of keys to deepGetOrNil. Key can be either:

  • number
  • array of Keys
  • anything else, which is toString()ed and dot-split.
const name = deget("name");
  
name({name: "Tom"});
// => "Tom"
  
const city = deget("address.city");
const city2 = deget("address", "city");
// and other forms, like:
// const city3 = deget(["address", "city"]);
// const city4 = deget("address", [[], "city"]);
// const city5 = deget([[], "address.city"]);
// etc.
const object = {address: {city: "New York"}};
  
city(object);
// => "New York"
city2(object);
// => "New York"
  
city(undefined);
// => undefined
city(null);
// => undefined
city({});
// => undefined
city({address: null});
// => undefined
city({address: {}});
// => undefined
city({address: {city: null}});
// => null

If you put a number in a list of keys to use, an object will be treated as an array.

That way you can create eg. const c = deget("person", 34, "name") to access obj.person[34].name with c(obj).

deepCopyOnWrite(key, ...)(val)

decow(key, ...)(val)

Creates a modifier function allowing to "set" specified key to any object in an immutable fashion, eg. creating a modified copy when actual write happens.

If properties that are to be parents of a sub-value are not present, they are created.

Specify keys by passing a list of keys to deepCopyOnWrite. Key can be either:

  • number
  • array of Keys
  • anything else, which is toString()ed and dot-split.

In case no change actually happens (same value is set which is already present), returns the original object.

const setName = decow("name");
  
setName("Jerry")({name: "Tom"});
// => {name: "Jerry"}
  
const setCity = decow("address.city");
const setCity2 = decow("address", "city");
// and other forms, like:
// const setCity3 = decow(["address", "city"]);
// const setCity4 = decow("address", [[], "city"]);
// const setCity5 = decow([[], "address.city"]);
// etc.
const object = {address: {city: "New York"}};
  
setCity("London")(object);
// => {address: {city: "London"}}
setCity2("London")(object);
// => {address: {city: "London"}}
object;
// => {address: {city: "New York"}}
setCity("New York")(object) === object;
// => true
setCity("New York")(object) === object;
// => true
  
const setCityLondon = setCity("London");
  
setCityLondon(undefined);
// => {address: {city: "London"}}
setCityLondon(null);
// => {address: {city: "London"}}
setCityLondon({});
// => {address: {city: "London"}}
setCityLondon({address: null});
// => {address: {city: "London"}}
setCityLondon({address: {}});
// => {address: {city: "London"}}
setCityLondon({address: {city: null}});
// => {address: {city: "London"}}

If you put a number in a list of keys to use, an object will be treated as an array (unlike the default string case, where it is treated as an object), so copy wil be created using [...obj], not using {...obj}.

That way you can create eg. const c = decow("person", 34, "name") to "set" obj.person[34].name with c(val)(obj).

cowValueModel(key, ...)

Deprecated.

Creates an overloaded function allowing to set or get specified key from any object.

It gets when one arg passed (works as deget(key, ...)), sets when two args (obj, val) passed (works as decow(key, ...)(val)(obj)), with a caveat: setting undefined ends up as plain get (ES2015 default arguments semantics), so props are not created when not present if setting undefined; other values including null are ok and create nonpresent props.

typedAction(type, [fn])

This creates an action creator function that amends existing fn by:

  • adding a type property to the result, as well as
  • adding a TYPE property to action creator itself.

So for example:

export const answerQuestion =
  typedAction("answer question", (index, answer) => ({
    payload: {index, answer}
  }));

allows you to call answerQuestion(2, "Albert Einstein") to create {type: "answer question", payload: {index: 2, answer: "Albert Einstein"}}; but it also allows you to use case answerQuestion.TYPE: in your reducer, since answerQuestion.TYPE === "answer question". IOW, this removes the two-space problem of having const FOO_BAR_TYPE as well as fooBar action creator.

In case you don't pass the fn argument, the action creator only creates {type}.

cowWorkshop(keys, fn = x => x)(obj, [options])

This is multipurpose enumerate-and-act function to manipulate objects using cowValueModel. The options argument can contain these additional fields:

  • result -- where to put elements (obj by default),
  • resultKeys -- what keys to use to put into result (keys by default)
  • diff -- where to put diffing elements (undefined by default)

Function enumerates over keys and performs "get key from obj, call fn on value, put transformed value into resultKey in result" operations over them, using cowValueModel for getting as well as putting. Additionally, if putting actually resulted in change, the result key and value is also put into diff. It then returns {result, diff} object.

cowWorkshop(["a", "b.c"])();
// does nothing
// => {result: undefined, diff: undefined}
  
cowWorkshop(["a", "b.c"], () => null)();
// sets a and b.c to null
// => {result: {a: null, b: {c: null}}, diff: {a: null, b: {c: null}}}
  
const data = {a: 'foo', b: {c: null}};
cowWorkshop(["a", "b.c"], JSON.stringify)(data);
// changes a and b.c to string representation; change to a is noop
// => {result: {a: 'foo', b: {c: 'null'}}, diff: {b: {c: 'null'}}}
  
const stored = {ay: 'bar', beecee: 'baz', cee: 'quux'};
const data = {a: 'foo', b: {c: null}};
cowWorkshop(["a", "b.c"])(data, {result: stored, resultKeys: ["ay", "beecee"]});
// "copies" a and b.c into `stored` under different keys
// => {result: {ay: 'foo', beecee: null, cee: 'quux'}, diff: {ay: 'foo', beecee: null}}
  
const data = {a: 'foo', b: {c: 'bar'}, c: 'quux'};
cowWorkshop(["a", "b.c"], () => null)(data);
// "nulls" a few fields
// => {result: {a: null, b: {c: null}, c: 'quux'}, diff: {a: null, b: {c: null}}}