Last active
May 16, 2018 17:35
-
-
Save DanyelMorales/e0ea821c1a0e71790abf2f76d1556d8f 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
import { JSONType } from "./IJsonType"; | |
/** | |
* Filtra un resultado de modo que se pueda modificar. | |
*/ | |
export class SimpleFilter<K> { | |
protected filters: JSONType<K, (data) => any>; | |
constructor() { | |
this.filters = new JSONType<K, (data) => any>(); | |
} | |
/** | |
* Agrega un nuevo filtro basado en lambdas de tipo T | |
* @param key | |
* @param value | |
*/ | |
addFilter<T>(key: K, value: (data) => T): SimpleFilter<K> { | |
this.filters.put(key, value); | |
return this; | |
} | |
addFilterGuard(key: K, value: (data) => Boolean): SimpleFilter<K> { | |
this.addFilter<Boolean>(key, value); | |
return this; | |
} | |
reset(): SimpleFilter<K> { | |
this.filters = new JSONType<K, (data) => any>(); | |
return this; | |
} | |
/** | |
* @param key | |
* @param data indice 0 deberia ser el principal dato a retornar, el resto son opciones | |
* @returns indice 0 del arreglo de argumentos que se ha pasado, | |
* si no existe filtro alguno | |
*/ | |
applyFilter<R>(key: K, data: any): R { | |
if (!this.filters.has(key)) { | |
return data; | |
} | |
const result: R = this.execFunction<R>(key, data); | |
if (result === null || result === undefined) { | |
return data; | |
} | |
return result; | |
} | |
/** | |
* Ejecuta funciones almacenados como filtros. | |
* @param key | |
* @param data | |
*/ | |
private execFunction<R>(key: K, data: any): R { | |
const fx: (data) => R = this.filters.get(key); | |
const result: R = fx(data); | |
return result; | |
} | |
/** | |
* Siempre retorna un booleano | |
* @param key filtro a ejecutar | |
* @param data datos a evaluar | |
*/ | |
applyGuard(key: K, data: any): Boolean { | |
return this.applyFilter<boolean>(key, data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment