Skip to content

Commit a2bd6aa

Browse files
authored
feat: 添加 composeFuncProps (#227)
* feat: 添加 unionRunFunc * fix: review * fix: review * fix: review * fix: reviw * fix: ts * fix: test * feat: review * feat: review * feat: review * feat: review
1 parent 6766ada commit a2bd6aa

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/composeProps.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function composeProps<T extends Record<string, any>>(
2+
originProps: T,
3+
patchProps: Partial<T>,
4+
isAll?: boolean,
5+
) {
6+
const composedProps: Record<string, any> = {
7+
...originProps,
8+
...(isAll ? patchProps : {}),
9+
};
10+
11+
Object.keys(patchProps).forEach(key => {
12+
const func = patchProps[key];
13+
if (typeof func === 'function') {
14+
composedProps[key] = (...args) => {
15+
func(...args);
16+
return originProps[key](...args);
17+
};
18+
}
19+
});
20+
return composedProps;
21+
}
22+
23+
export default composeProps;

tests/composeProps.test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import composeProps from '../src/composeProps';
2+
3+
describe('composeProps', () => {
4+
it('composeProps all', () => {
5+
const aChange = jest.fn();
6+
const aBlur = jest.fn();
7+
const bChange = jest.fn();
8+
const sourceProps = { value: '11', onChange: aChange, onBlur: aBlur };
9+
const patchProps = { onChange: bChange, placeholder: 'x' };
10+
11+
const props = composeProps(sourceProps, patchProps, true);
12+
props.onChange();
13+
props.onBlur();
14+
expect(aChange).toHaveBeenCalled();
15+
expect(aBlur).toHaveBeenCalled();
16+
expect(bChange).toHaveBeenCalled();
17+
expect(Object.keys(props)).toEqual([
18+
'value',
19+
'onChange',
20+
'onBlur',
21+
'placeholder',
22+
]);
23+
});
24+
it('composeProps just func', () => {
25+
const aChange = jest.fn();
26+
const aBlur = jest.fn();
27+
const bChange = jest.fn();
28+
const sourceProps = { value: '11', onChange: aChange, onBlur: aBlur };
29+
const patchProps = { onChange: bChange, placeholder: 'x' };
30+
31+
const props = composeProps(sourceProps, patchProps);
32+
props.onChange();
33+
props.onBlur();
34+
expect(aChange).toHaveBeenCalled();
35+
expect(aBlur).toHaveBeenCalled();
36+
expect(bChange).toHaveBeenCalled();
37+
expect(Object.keys(props)).toEqual(['value', 'onChange', 'onBlur']);
38+
});
39+
});

0 commit comments

Comments
 (0)