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