Created
April 28, 2018 12:31
-
-
Save sanex3339/084b0d42d4526cc7fe377530e5f39887 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Condition<T> = {shouldApply: boolean, conditionFunc: ((item: T) => boolean)}; | |
/** | |
* Фильтрует данные на основе массива ф-ий условий | |
* В случае отсутствия фильтров или когда не применен ни один фильтр - возвращается оригинальный массив данных | |
*/ | |
export class ConditionFilter <T> { | |
/** | |
* Константа, для того, чтобы всегда применять фильтр | |
*/ | |
public static APPLY: boolean = true; | |
/** | |
* Данные | |
*/ | |
private readonly data: T[]; | |
/** | |
* Массив условий | |
*/ | |
private conditions: Condition <T> [] = []; | |
constructor(data: T[]) { | |
this.data = data; | |
} | |
/** | |
* Добавляет новое условие | |
*/ | |
public addCondition(shouldApply: boolean, conditionFunc: (item: T) => boolean): this { | |
this.conditions.push({shouldApply, conditionFunc}); | |
return this; | |
} | |
/** | |
* Выполняет фильтрацию | |
*/ | |
public filter(): T[] { | |
let isFilterWasApplied: boolean = false; | |
const filteredData: T[] = this.data.reduce( | |
(filteredData: T[], item: T) => { | |
let isFilteredItem: boolean = true; | |
for (const condition of this.conditions) { | |
const {shouldApply, conditionFunc} = condition; | |
if (!shouldApply) { | |
continue; | |
} | |
isFilterWasApplied = true; | |
isFilteredItem = conditionFunc(item); | |
if (!isFilteredItem) { | |
break; | |
} | |
} | |
if (!isFilteredItem) { | |
return filteredData; | |
} | |
return [...filteredData, item]; | |
}, | |
[] | |
); | |
return isFilterWasApplied ? filteredData : this.data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment