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

Commit

Permalink
fix(util): remove empty key was removing non object key (#29)
Browse files Browse the repository at this point in the history
* fix(util): remove empty key was removing non object key

* wip
  • Loading branch information
mthuret authored Apr 13, 2017
1 parent fb1eb6c commit 9f795c7
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 10 deletions.
19 changes: 9 additions & 10 deletions packages/react-instantsearch/src/core/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isEmpty } from 'lodash';
import { isEmpty, isPlainObject } from 'lodash';

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

export function removeEmptyKey(obj) {
Object.keys(obj).forEach(
key =>
(obj[key] &&
typeof obj[key] === 'object' &&
!isEmpty(obj[key]) &&
removeEmptyKey(obj[key])) ||
obj[key] === undefined ||
(isEmpty(obj[key]) && delete obj[key])
);
Object.keys(obj).forEach(key => {
const value = obj[key];
if (isEmpty(value) && isPlainObject(value)) {
delete obj[key];
} else if (isPlainObject(value)) {
removeEmptyKey(value);
}
});
return obj;
}
62 changes: 62 additions & 0 deletions packages/react-instantsearch/src/core/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
assertFacetDefined,
getDisplayName,
defer,
removeEmptyKey,
} from './utils';

import { SearchParameters, SearchResults } from 'algoliasearch-helper';
Expand Down Expand Up @@ -110,4 +111,65 @@ describe('utils', () => {
});
});
});
describe('remove empty key', () => {
it('empty key should be removed', () => {
const state = {
query: '',
page: 2,
sortBy: 'mostPopular',
range: {
price: {
min: 20,
max: 3000,
},
},
refinementList: {},
indices: {
index1: {
configure: {
hitsPerPage: 3,
refinementList: {},
},
},
index2: {
configure: {
hitsPerPage: 10,
},
refinementList: {
fruits: ['lemon', 'orange'],
},
},
},
};

const newState = removeEmptyKey(state);

expect(newState).toEqual({
query: '',
page: 2,
sortBy: 'mostPopular',
range: {
price: {
min: 20,
max: 3000,
},
},
indices: {
index1: {
configure: {
hitsPerPage: 3,
},
},
index2: {
configure: {
hitsPerPage: 10,
},
refinementList: {
fruits: ['lemon', 'orange'],
},
},
},
});
});
});
});

0 comments on commit 9f795c7

Please sign in to comment.