Skip to content

Commit

Permalink
fix(react): refactor/rest op (#860)
Browse files Browse the repository at this point in the history
* refactor restOp wit typing and better perfomance

* test for restOp

* fix downgrade es6 method

Co-authored-by: Roman Sokhan <pustomytnyk@gmail.com>
Co-authored-by: Denis Skiba <dskiba@docdoc.ru>
  • Loading branch information
3 people authored Nov 5, 2021
1 parent 1c74881 commit da94704
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
23 changes: 23 additions & 0 deletions packages/react/__tests__/styled.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { restOp } from '../src/styled';

const React = require('react');
const renderer = require('react-test-renderer');
const styled = require('../src').styled;
Expand Down Expand Up @@ -254,3 +256,24 @@ it('throws when using as tag for template literal', () => {
`
).toThrow('Using the "styled" tag in runtime is not supported');
});

it('can get rest keys from object', () => {
const obj = { one: 1, two: 2, three: 3 };
const rest = restOp(obj, ['two']);
// eslint-disable-next-line no-unused-vars
const { two, ...expectedRest } = obj;
expect(rest).toEqual(expectedRest);
});
it('can get rest keys from complex object', () => {
const obj = {
string: 'hello',
bool: false,
object: { hello: 'world' },
arr: [1, 2, 3],
num: 47,
};
const rest = restOp(obj, ['bool', 'object', 'arr']);
// eslint-disable-next-line no-unused-vars
const { bool, object, arr, ...expectedRest } = obj;
expect(rest).toEqual(expectedRest);
});
26 changes: 16 additions & 10 deletions packages/react/src/styled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,23 @@ type Options = {
};
};

interface CustomOmit {
<T extends object, K extends [...(keyof T)[]]>(obj: T, keys: K): {
[K2 in Exclude<keyof T, K[number]>]: T[K2];
};
}

// Workaround for rest operator
const restOp = (
obj: Record<string, unknown>,
keysToExclude: string[]
): Record<string, unknown> =>
Object.keys(obj)
.filter((prop) => keysToExclude.indexOf(prop) === -1)
.reduce((acc, curr) => {
acc[curr] = obj[curr];
return acc;
}, {} as Record<string, unknown>); // rest operator workaround
export const restOp: CustomOmit = (obj, keys) => {
const res = {} as { [K in keyof typeof obj]: typeof obj[K] };
let key: keyof typeof obj;
for (key in obj) {
if (keys.indexOf(key) === -1) {
res[key] = obj[key];
}
}
return res;
};

const warnIfInvalid = (value: any, componentName: string) => {
if (process.env.NODE_ENV !== 'production') {
Expand Down

0 comments on commit da94704

Please sign in to comment.