Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/composeProps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function composeProps<T extends Record<string, any>>(
originProps: T,
patchProps: Partial<T>,
isAll?: boolean,
) {
const composedProps: Record<string, any> = {
...originProps,
...(isAll ? patchProps : {}),
};

Object.keys(patchProps).forEach(key => {
const func = patchProps[key];
if (typeof func === 'function') {
composedProps[key] = (...args) => {
func(...args);
return originProps[key](...args);
};
}
});
return composedProps;
}

export default composeProps;
39 changes: 39 additions & 0 deletions tests/composeProps.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import composeProps from '../src/composeProps';

describe('composeProps', () => {
it('composeProps all', () => {
const aChange = jest.fn();
const aBlur = jest.fn();
const bChange = jest.fn();
const sourceProps = { value: '11', onChange: aChange, onBlur: aBlur };
const patchProps = { onChange: bChange, placeholder: 'x' };

const props = composeProps(sourceProps, patchProps, true);
props.onChange();
props.onBlur();
expect(aChange).toHaveBeenCalled();
expect(aBlur).toHaveBeenCalled();
expect(bChange).toHaveBeenCalled();
expect(Object.keys(props)).toEqual([
'value',
'onChange',
'onBlur',
'placeholder',
]);
});
it('composeProps just func', () => {
const aChange = jest.fn();
const aBlur = jest.fn();
const bChange = jest.fn();
const sourceProps = { value: '11', onChange: aChange, onBlur: aBlur };
const patchProps = { onChange: bChange, placeholder: 'x' };

const props = composeProps(sourceProps, patchProps);
props.onChange();
props.onBlur();
expect(aChange).toHaveBeenCalled();
expect(aBlur).toHaveBeenCalled();
expect(bChange).toHaveBeenCalled();
expect(Object.keys(props)).toEqual(['value', 'onChange', 'onBlur']);
});
});