2020-07-14 12:09:14 +00:00
|
|
|
import { uniqWith, isEqual } from 'lodash';
|
|
|
|
|
|
|
|
import { MAX_HISTORY_SIZE } from '../constants';
|
2017-03-30 02:04:05 +00:00
|
|
|
|
|
|
|
class RecentSearchesStore {
|
2017-05-23 16:35:54 +00:00
|
|
|
constructor(initialState = {}, allowedKeys) {
|
2020-05-07 21:09:26 +00:00
|
|
|
this.state = {
|
|
|
|
isLocalStorageAvailable: true,
|
|
|
|
recentSearches: [],
|
|
|
|
allowedKeys,
|
|
|
|
...initialState,
|
|
|
|
};
|
2017-03-30 02:04:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
addRecentSearch(newSearch) {
|
|
|
|
this.setRecentSearches([newSearch].concat(this.state.recentSearches));
|
|
|
|
|
|
|
|
return this.state.recentSearches;
|
|
|
|
}
|
|
|
|
|
|
|
|
setRecentSearches(searches = []) {
|
2020-07-14 12:09:14 +00:00
|
|
|
const trimmedSearches = searches.map(search =>
|
|
|
|
typeof search === 'string' ? search.trim() : search,
|
|
|
|
);
|
|
|
|
|
|
|
|
// Do object equality check to remove duplicates.
|
|
|
|
this.state.recentSearches = uniqWith(trimmedSearches, isEqual).slice(0, MAX_HISTORY_SIZE);
|
2017-03-30 02:04:05 +00:00
|
|
|
return this.state.recentSearches;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default RecentSearchesStore;
|