github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/ui/app/mixins/searchable.js (about)

     1  import Ember from 'ember';
     2  
     3  const { Mixin, computed, get } = Ember;
     4  
     5  /**
     6    Searchable mixin
     7  
     8    Simple search filtering behavior for a list of objects.
     9  
    10    Properties to override:
    11      - searchTerm: the string to use as a query
    12      - searchProps: the props on each object to search
    13      - listToSearch: the list of objects to search
    14  
    15    Properties provided:
    16      - listSearched: a subset of listToSearch of items that meet the search criteria
    17  */
    18  export default Mixin.create({
    19    searchTerm: '',
    20    listToSearch: computed(() => []),
    21    searchProps: null,
    22  
    23    listSearched: computed('searchTerm', 'listToSearch.[]', 'searchProps.[]', function() {
    24      const searchTerm = this.get('searchTerm');
    25      if (searchTerm && searchTerm.length) {
    26        return regexSearch(searchTerm, this.get('listToSearch'), this.get('searchProps'));
    27      }
    28      return this.get('listToSearch');
    29    }),
    30  });
    31  
    32  function regexSearch(term, list, keys) {
    33    if (term.length) {
    34      try {
    35        const regex = new RegExp(term, 'i');
    36        // Test the value of each key for each object against the regex
    37        // All that match are returned.
    38        return list.filter(item => keys.some(key => regex.test(get(item, key))));
    39      } catch (e) {
    40        // Swallow the error; most likely due to an eager search of an incomplete regex
    41      }
    42    }
    43  }