Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable.
The Group
class represents a collection of values, akin to a Set
, equipped with methods for adding, removing, and checking elements within the set.
The initial step of crafting the class was tackled gracefully thanks to the guidance in my textbook. Through verifying the solution provided and running tests, I can affirm its accuracy. However, my struggles arise starting from the [Symbol.iterator]
aspect onwards.
Below lies the code snippet:
class Group {
constructor() {
this.theGroup = [];
}
add( element ) {
if( !this.has(element) ) this.theGroup.push(element);
}
remove( element ) {
this.theGroup = this.theGroup.filter( x => x != element );
}
has( element ) {
return this.theGroup.includes(element);
}
static from( elements ) {
let group = new Group;
for( const x of elements ) {
group.add(x);
}
return group;
}
[Symbol.iterator]() {
let i = 0;
return next = () => {
if( i >= this.theGroup.length ) return { done : true };
else return { value : this.theGroup[i++], done : false };
};
}
}
// The subsequent segment serves merely to exhibit that the code preceding [Symbol.iterator] functions correctly
const group = Group.from([10, 20]);
console.log(group.has(10));
group.add(10);
group.remove(10);
console.log(group.has(10));
group.remove(10);
console.log(group.has(20));
// Conclusion of demonstration
for (let value of Group.from(["a", "b", "c"])) {
console.log(value);
}
An error is triggered when executing the code:
return next = () => {
^
ReferenceError: next is not defined
Switching the arrow function to an anonymous one like so:
return () => { ...further code progresses
brings forth an alternative issue:
for (let value of Group.from(["a", "b", "c"])) {
^
TypeError: undefined is not a function
My preference for utilizing an arrow function stems from wanting to circumvent altering this
.
If anyone has insights on what may be causing this predicament,
How could I transform the class into an iterable version?