Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Function Composition to not rely out `this`
/* Similar to recompose withProps but for object composition */
export const withProps = (extension) => (state) => {
const ext = extension(state);
return {
...state,
...ext,
};
};
export const compose = (...fns) => (state) => {
let reduced = {};
fns.forEach((f) => {
reduced = {
...reduced,
...f({
...reduced,
...state,
}),
};
});
return reduced;
};
import { compose } from './composition';
import withA from './withA';
import withB from './withB';
import withC from './withC';
const composed = ({ aVal, bVal, cVal }) =>
compose(
withA,
withB,
withC,
)({ a: { val: aVal }, b: { val: bVal }, c: { val: cVal } });
export default composed;
import { withProps } from './composition';
const withA = withProps(({ a: { value } }) => {
const log = () => console.log(value);
const getValue = () => value;
const longTimeFunction = Promise.try(() => ....doSomething);
return { a: { log, longTimeFunction, getValue } };
});
export default withA;
import { withProps } from './composition';
const withB = withProps(({ b: { value } }) => {
const getValue = () => value;
const uniqueTo = Promise.try(() => ....doSomething);
return { b: { log, uniqueTo, getValue } };
});
export default withB;
import { withProps } from './composition';
const withC = withProps(({ c: { value } }) => {
const getValue = () => value;
const uniqueTo = Promise.try(() => ....doSomething);
return { c: { log, uniqueTo, getValue } };
});
export default withC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.