Skip to content

Commit

Permalink
refactor(utils): rename appendProps to pluckProps
Browse files Browse the repository at this point in the history
apply correct typing

BREAKING CHANGE: appendProps is now renamed pluckProps
  • Loading branch information
aneurysmjs committed Oct 6, 2019
1 parent 9e47807 commit 8045f8a
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/app/shared/utils/pluckProps/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './pluckProps';
52 changes: 52 additions & 0 deletions src/app/shared/utils/pluckProps/pluckProps.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import pluckProps from './pluckProps';

type Obj = {
a: 1;
b: 2;
};

describe('pluckProps', () => {
it('should return a function', () => {
const fn = pluckProps<Obj>('a');
expect(typeof fn).toEqual('function');
});

it('should return an object with property "a" and ignore the rest', () => {
const fn = pluckProps<Obj>('a');
const obj = fn({ a: 1, b: 2 });
expect(obj).toEqual({ a: 1 });
});

it('should return an object with properties "a" and "b"', () => {
const fn = pluckProps<Obj>('a', 'b');
const obj = fn({ a: 1, b: 2 });
expect(obj).toEqual({ a: 1, b: 2 });
});

it('should return an object with property "b"', () => {
const fn = pluckProps<Obj>('b');
const obj = fn({ a: 1, b: 2 });
expect(obj).toEqual({ b: 2 });
});

// eslint-disable-next-line prettier/prettier
it('should return empty object if the given object doesn\'t match with properties to reflect', () => {
const fn = pluckProps<Obj>('a', 'b');
const obj = fn({ c: 3, d: 4 });
expect(obj).toEqual({});
});

// eslint-disable-next-line prettier/prettier
it('should return empty object if there\'s not properties to append', () => {
const fn = pluckProps<Obj>();
const obj = fn({ a: 1, b: 2 });
expect(obj).toEqual({});
});
// eslint-disable-next-line prettier/prettier
it('should throw if there\'s not object to reflect', () => {
const fn = pluckProps<Obj>('a', 'b');
expect(() => {
fn();
}).toThrow();
});
});
17 changes: 17 additions & 0 deletions src/app/shared/utils/pluckProps/pluckProps.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* @desc: conditionally append properties as they're defined
*/

type AppendProps = <T>(...args: Array<keyof T>) => (obj: T) => T | Partial<T>;

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const pluckProps: AppendProps = (...args) => obj =>
args.reduce(
(acc, arg) => ({
...acc,
...(obj[arg] && { [arg]: obj[arg] }),
}),
{},
);

export default pluckProps;

0 comments on commit 8045f8a

Please sign in to comment.