Skip to content

Instantly share code, notes, and snippets.

@rxluz
Created January 18, 2019 08:35
Show Gist options
  • Select an option

  • Save rxluz/c87895b48a5146aaa3358d6bb4d6df3c to your computer and use it in GitHub Desktop.

Select an option

Save rxluz/c87895b48a5146aaa3358d6bb4d6df3c to your computer and use it in GitHub Desktop.
JS Design Patterns: Iterator, see more at: https://medium.com/p/b890884326a8
class Car {
constructor({ model, year, manufacturer }) {
this.setYear(year);
this.setManufacturer(manufacturer);
this.setModel(model);
}
setModel(model) {
this.model = model;
}
setYear(year) {
this.year = year;
}
setManufacturer(manufacturer) {
this.manufacturer = manufacturer;
}
}
class CarIterator {
constructor(carsList) {
this.list = carsList;
this.current = 0;
}
first() {
return this.list[0];
}
next() {
return this.list[++this.current];
}
isDone() {
return this.current === this.list.length;
}
currentItem() {
return this.list[this.current];
}
}
const run = () => {
const carsList = [
new Car({ model: "Corolla", manufacturer: "Toyota", year: 2013 }),
new Car({ model: "Polo", manufacturer: "Volks", year: 2017 }),
new Car({ model: "Civic", manufacturer: "Honda", year: 2015 }),
new Car({ model: "Tucson", manufacturer: "Hyundai", year: 2015 }),
];
const carInteratorInstance = new CarIterator(carsList);
console.log(carInteratorInstance.currentItem(), "currentItem");
console.log(carInteratorInstance.next(), "next");
console.log(carInteratorInstance.next(), "next");
console.log(carInteratorInstance.first(), "first");
console.log(carInteratorInstance.isDone(), "isDone");
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment