Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WouterSpaak/9a9eed375ead33688e688c0ddce0db8d to your computer and use it in GitHub Desktop.
Save WouterSpaak/9a9eed375ead33688e688c0ddce0db8d to your computer and use it in GitHub Desktop.
class Filter<T> {
static greaterThan(threshold: number, orEqualTo: boolean = false) {
return (input: number) => orEqualTo ? input >= threshold : input > threshold;
}
static equalTo(compare: number | string) {
return (input: number | string) => input === compare;
}
constructor(private readonly collection: Array<T>) { }
where<V>(prop: keyof T, predicate: (item: T[keyof T]) => V) {
const filtered = this.collection.filter(item => predicate(item[prop]));
if (!filtered.length) {
throw new RangeError(`No more items in collection! :(`);
}
return new Filter(filtered);
}
// finally, let's be able access our initial array
toArray() {
return this.collection;
}
}
class Person {
constructor(public age: number, public firstName: string, public lastName: string) { }
}
const myPersons = [
new Person(15, 'Alice', 'Cage'),
new Person(21, 'Bob', 'Johnson'),
new Person(32, 'Johnny', 'Appleseed'),
];
const myFilter = new Filter(myPersons);
const myResult = myFilter
.where('age', Filter.greaterThan(20) as any)
.where('firstName', Filter.equalTo('Johnny'))
.toArray();
console.log(myResult.map(person => `${person.firstName} ${person.lastName}`));
// -> Logs [ 'Johnny Appleseed' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment