Skip to content

Instantly share code, notes, and snippets.

@Furizaa
Last active September 22, 2016 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Furizaa/fdcc06425942afcd8a59007ff5fe91f8 to your computer and use it in GitHub Desktop.
Save Furizaa/fdcc06425942afcd8a59007ff5fe91f8 to your computer and use it in GitHub Desktop.
const bindSelectors = (selectors, stateSlice) =>
Object.keys(selectors).reduce((prev, curr) =>
({ ...prev, [curr]: (...args) => {
const [state, ...rest] = args;
return selectors[curr](state[stateSlice], ...rest);
}}),
{}
);
// State
const _state = {
value: 'A',
b: {
value: 'B',
c: {
value1: 7,
value2: 12,
},
},
};
// File C (Very deep)
const fromC = {
getC1: state => state.value1,
getC2: state => state.value2,
};
// File B (Has access to C and itself)
const inheritedFromC = bindSelectors(fromC, 'c');
const fromB = {
...inheritedFromC,
getAllC: state => inheritedFromC.getC1(state) + inheritedFromC.getC2(state),
getB: (state, extra) => state.value + extra,
};
// File A
const inheritedFromB = bindSelectors(fromB, 'b');
const fromA = {
...inheritedFromB,
getA: state => state.value,
};
// RESULT (state tree is no concern anymore)
fromA.getA(_state); // "A"
fromA.getB(_state, ' foo'); // "B foo"
fromA.getAllC(_state); // 19
fromA.getC1(_state); // 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment