Search This Blog

2023/04/20

Iterator Design Pattern in javascript

 In JavaScript, an iterator is an object that provides a way to access elements in

a collection (such as an array) sequentially, one at a time, without having to
know the underlying structure of the collection. The Iterator class is
not a built-in class in JavaScript, but rather a concept or pattern that
can be implemented by any class that wants to provide an iterator for its
elements.


Here is Example:

class Course {
constructor(title, description, price) {
this.title = title;
this.description = description;
this.price = price;
}
}

class CourseList {
constructor() {
this.courses = [];
}

addCourse(course) {
this.courses.push(course);
}

toArray() {
return [...this.courses];
}

[Symbol.iterator]() {
let index = 0;
const courses = this.courses;
return {
next: () => {
if (index < courses.length) {
return { value: courses[index++], done: false };
}
return { done: true };
},
};
}
}

const courseList = new CourseList();

courseList.addCourse(new Course("JavaScript", "JavaScript from scratch", 99));
courseList.addCourse(new Course("React", "Learn React from scratch", 149));
courseList.addCourse(new Course("Node.js", "Learn Node.js from scratch", 199));

for (const course of courseList) {
console.log(course.title, course.description, course.price);
}

courseList.toArray().forEach((element) => {
console.log(element)
});


[Symbol.iterator] is a symbol in JavaScript that represents the special
iterator method of an object.

Another Implementation

class Iterator {
constructor(items) {
this.index = 0;
this.items = items;
}

first() {
this.reset();
return this.items[0]
}
next() {
return this.items[ ++this.index];
}
hasNext() {
return this.index < this.items.length;
}
reset() {
this.index = 0;
}
foreach(callback) {
for (var item = this.first(); this.hasNext(); item = this.next()) {
callback(item);
}
}

[Symbol.iterator]() {
this.reset()
return {
next: () => {
if (this.index < this.items.length) {
const value = this.items[this.index];
this.index++;
return { done: false, value: value };
} else {
return { done: true };
}
},
};
}


}


var items = ["one", 2, "circle", true, "Applepie"];
var iter = new Iterator(items);

console.log("-------------with for---------------")
for (var item = iter.first(); iter.hasNext(); item = iter.next()) {
console.log(item);
}

console.log("-----------------with foreach--------------------")
iter.foreach(function (item) {
console.log(item);
});



console.log("--------------with for of---------------")
//iter.reset()
for (const elem of iter) {
console.log(elem);
}

console.log("--------------with for of---------------")
for (const elem of iter) {
console.log(elem);
}

No comments:

Post a Comment