|
| 1 | +import {Pipe, PipeTransform} from "@angular/core"; |
| 2 | + |
| 3 | +@Pipe({ |
| 4 | + name: 'filterBy' |
| 5 | +}) |
| 6 | +export class FilterBy implements PipeTransform { |
| 7 | + private filterByString(filter){ |
| 8 | + filter = filter.toLowerCase(); |
| 9 | + return value => { |
| 10 | + return !filter || value.toLowerCase().indexOf(filter) !== -1; |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + private filterByObject(filter) { |
| 15 | + return value => { |
| 16 | + for (let key in filter) { |
| 17 | + if (!value.hasOwnProperty(key)) { |
| 18 | + return false; |
| 19 | + } |
| 20 | + if (filter[key] == null){ |
| 21 | + return true; |
| 22 | + } |
| 23 | + |
| 24 | + const type = typeof value[key]; |
| 25 | + let isMatching; |
| 26 | + |
| 27 | + if (type === 'string') { |
| 28 | + isMatching = this.filterByString(filter[key])(value[key]); |
| 29 | + } else if (type === 'object') { |
| 30 | + isMatching = this.filterByObject(filter[key])(value[key]); |
| 31 | + } else { |
| 32 | + isMatching = this.filterDefault(filter[key])(value[key]); |
| 33 | + } |
| 34 | + |
| 35 | + if (!isMatching) { |
| 36 | + return false; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return true; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Defatul filterDefault function |
| 46 | + * |
| 47 | + * @param filter |
| 48 | + * @returns {(value:any)=>boolean} |
| 49 | + */ |
| 50 | + private filterDefault(filter) { |
| 51 | + return value => { |
| 52 | + return !filter || filter == value; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + transform(array: any[], filter: string): any { |
| 57 | + if(array==null){ |
| 58 | + return null; |
| 59 | + } |
| 60 | + const type = typeof filter; |
| 61 | + |
| 62 | + if(type === 'string'){ |
| 63 | + console.log("IMA STRING! WUTTTTT!"); |
| 64 | + return array.filter(this.filterByString(filter)); |
| 65 | + } |
| 66 | + |
| 67 | + if(type == 'object'){ |
| 68 | + return array.filter(this.filterByObject(filter)); |
| 69 | + } else { |
| 70 | + console.log("Unknown filter type???"); |
| 71 | + console.log(type); |
| 72 | + console.log(filter); |
| 73 | + return array; |
| 74 | + } |
| 75 | + |
| 76 | + } |
| 77 | +} |
0 commit comments