Last active
January 13, 2019 01:29
-
-
Save miladvafaeifard/25ad7c3f0ba8776944defb4cd2dc39c2 to your computer and use it in GitHub Desktop.
Iterator pattern
This file contains hidden or 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
export interface Iterator<T> { | |
next(): T; | |
hasNext(): boolean; | |
} | |
export interface Aggregator<T> { | |
createIterator(): Iterator<T>; | |
} | |
export class ConcreteIterator<IteratorType> implements Iterator<IteratorType> { | |
private collection: IteratorType[] = []; | |
private position: number = 0; | |
constructor(collection: IteratorType[]) { | |
this.collection = collection; | |
} | |
public next(): IteratorType { | |
if(this.position < this.collection.length){ | |
var result = this.collection[this.position]; | |
this.position += 1; | |
return result; | |
} else { | |
return null; | |
} | |
} | |
public hasNext(): boolean { | |
return this.position < this.collection.length; | |
} | |
} | |
export class Numbers implements Aggregator<number> { | |
private collection: number[] = []; | |
constructor(collection: number[]) { | |
this.collection = collection; | |
} | |
public createIterator(): Iterator<number> { | |
return new ConcreteIterator(this.collection); | |
} | |
} | |
class Employee { | |
public id: number; | |
public name: string | |
} | |
export class Employees implements Aggregator<Employee> { | |
private employees: Employee[]; | |
constructor(employees: Employee[]) { | |
this.employees = employees; | |
} | |
createIterator(): Iterator<Employee> { | |
return new ConcreteIterator(this.employees); | |
} | |
} | |
const list: Employee[] = [ | |
{id: 1, name: 'Milad'}, | |
{id: 2, name: 'Alexandra'} | |
]; | |
const employees = new Employees(list); | |
const iterator = employees.createIterator(); | |
console.log(iterator.next().name); // { id: 1, name: 'Milad' } | |
console.log(iterator.next()); // { id: 2, name: 'Alexandra' } | |
console.log(iterator.next()); // null | |
console.log(iterator.next()); // null | |
console.log(iterator.next()); // null | |
console.log(iterator.next()); // null | |
console.log(iterator.next()); // null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment