Published Apr 12, 2022
[
 
]
An old radio set will be a good example of iterator, where user could start at some channel and then use next or previous buttons to go through the respective channels. Or take an example of MP3 player or a TV set where you could press the next and previous buttons to go through the consecutive channels or in other words they all provide an interface to iterate through the respective channels, songs or radio stations.
It presents a way to access the elements of an object without exposing the underlying presentation.
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
First of all we have RadioStation
export class RadioStation {
protected frequency
constructor(frquency: number) {
this.frequency = frquency
}
getFrequency(): number {
return this.frequency
}
}
Then we have our iterator
export class StationList implements IterableIterator<RadioStation> {
protected pointer: number = 0;
protected stations: RadioStation[] = [];
addStation(station: RadioStation) {
this.stations.push(station)
}
next(): IteratorResult<RadioStation>{
if(this.pointer < this.stations.length) {
return {
done: false,
value: this.stations[this.pointer++]
}
} else {
return {
done: true,
value: null
}
}
}
[Symbol.iterator](): IterableIterator<RadioStation>{
return this;
}
}
And then it can be used as
test('IterableIterator next() interface', () => {
const stationList = new StationList()
const res = [89, 101, 102, 103.2];
for(let value of res) {
stationList.addStation(new RadioStation(value))
}
let count = 0;
while(true){
let station = stationList.next();
if(station.done){
break
}
expect(station.value.frequency).toEqual(res[count++])
}
})
test('IterableIterator let...of interface', () => {
const stationList = new StationList()
const res = [89, 101, 102, 103.2];
for(let value of res) {
stationList.addStation(new RadioStation(value))
}
let count = 0;
for(let station of stationList){
expect(station.getFrequency()).toEqual(res[count++]);
}
})