summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/filtered_search/stores/recent_searches_store.js
blob: ca0a58137b1dadddaa351b07361f0df26fed1f2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { uniqWith, isEqual } from 'lodash';

import { MAX_HISTORY_SIZE } from '../constants';

class RecentSearchesStore {
  constructor(initialState = {}, allowedKeys) {
    this.state = {
      isLocalStorageAvailable: true,
      recentSearches: [],
      allowedKeys,
      ...initialState,
    };
  }

  addRecentSearch(newSearch) {
    this.setRecentSearches([newSearch].concat(this.state.recentSearches));

    return this.state.recentSearches;
  }

  setRecentSearches(searches = []) {
    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);
    return this.state.recentSearches;
  }
}

export default RecentSearchesStore;