Skip to content
This repository has been archived by the owner on Dec 30, 2022. It is now read-only.

Commit

Permalink
refactor(lodash): isPlainObject
Browse files Browse the repository at this point in the history
The values this function was used for seemed like they can only be arrays or objects to me.

We will only want to empty out "breadth-first", so empty objects will stay in the output if they became empty because of the function itself.

isEmpty here is removed in #2442, and still works the same (but will need a rebase)

The newly added tests also pass with the previous implementation

The function is only used in `onSearchStateChange` as a response to a `cleanUp` (caused by unmount) on a widget

IFW-743
  • Loading branch information
Haroenv committed May 16, 2019
1 parent 4670c07 commit ff30a2f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
21 changes: 20 additions & 1 deletion packages/react-instantsearch-core/src/core/__tests__/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('utils', () => {
});
});

describe('remove empty key', () => {
describe.only('remove empty key', () => {
it('empty key should be removed', () => {
const state = {
query: '',
Expand Down Expand Up @@ -98,6 +98,25 @@ describe('utils', () => {
},
});
});

it('does not do anything on empty root', () => {
expect(utils.removeEmptyKey({})).toEqual({});
});

it('does empty out objects', () => {
expect(utils.removeEmptyKey({ test: {} })).toEqual({});
expect(utils.removeEmptyKey({ test: { dog: {} } })).toEqual({
// this one stays, because we have no multipass algorithm
test: {},
});
});

it('does not empty out arrays', () => {
expect(utils.removeEmptyKey({ test: [] })).toEqual({ test: [] });
expect(utils.removeEmptyKey({ test: { dog: [] } })).toEqual({
test: { dog: [] },
});
});
});

describe('addAbsolutePositions', () => {
Expand Down
18 changes: 12 additions & 6 deletions packages/react-instantsearch-core/src/core/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isEmpty, isPlainObject } from 'lodash';
import { isEmpty } from 'lodash';

// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
export const shallowEqual = (objA, objB) => {
Expand Down Expand Up @@ -33,13 +33,19 @@ export const defer = f => {
resolved.then(f);
};

export const removeEmptyKey = obj => {
const isPlainObject = (value: any): value is object =>
typeof value === 'object' && value !== null && !Array.isArray(value);

export const removeEmptyKey = (obj: object) => {
Object.keys(obj).forEach(key => {
const value = obj[key];
if (isEmpty(value) && isPlainObject(value)) {
if (!isPlainObject(obj[key])) {
return;
}

if (isEmpty(obj[key])) {
delete obj[key];
} else if (isPlainObject(value)) {
removeEmptyKey(value);
} else {
removeEmptyKey(obj[key]);
}
});

Expand Down

0 comments on commit ff30a2f

Please sign in to comment.