Skip to content

Instantly share code, notes, and snippets.

@potench
Created February 20, 2019 22:59
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 potench/631450fa4e2a1899505fbee438e62dda to your computer and use it in GitHub Desktop.
Save potench/631450fa4e2a1899505fbee438e62dda to your computer and use it in GitHub Desktop.
Compose 2 JS objects
/* @flow */
const compose = (...objects: *) =>
objects.reduce((merged, current) => {
Object.keys(current).forEach(methodKey => {
if (typeof current[methodKey] === 'function' && merged[methodKey]) {
const mergedMethod = merged[methodKey];
// eslint-disable-next-line no-param-reassign
merged[methodKey] = (...args) => {
const mergedResult = mergedMethod(...args);
const currentResult = current[methodKey](...args);
return mergedResult || currentResult;
};
} else {
merged[methodKey] = current[methodKey]; // eslint-disable-line no-param-reassign
}
});
return merged;
});
export default compose;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment