Having difficulty converting an object into an iterable using an arrow function

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?

Answer №1

To retrieve an object containing the key 'next',.

for example.. { next: () => {}} not return next = () => {}

Improved illustration below..

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 code following is necessary to demonstrate functionality before [Symbol.iterator]

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));

// End of demonstration

for (let value of Group.from(["a", "b", "c"])) {
  console.log(value);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for v-model not functioning properly?

Embarking on my Vue.js coding journey, I am currently following a straightforward online tutorial. Utilizing the vue-cli, I kickstarted my application and crafted a basic component named Test.vue. Within this component lies a simplistic input control conne ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

Mongoose Alert: Unable to Create Schema Instance

Below is the Schema file that I'm using: const mongoose = require("mongoose"); const ProblemSchema = new mongoose.Schema( { slug: { type: String, required: true, unique: true, }, title: { type: String, ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

Tips for sending a changing mouse scroll value as a property in VueJS

I am currently utilizing the Laravel - VueJS framework. My goal is to detect the Y position of the mouse scroll and pass it dynamically as a prop to a Navbar component. To achieve this, I set up an eventListener and stored the window.scrollY value in a va ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Achieving a dynamic "Picture Presentation" feature with JavaScript/jQuery

Currently, I am in the process of developing a website that will serve as a presentation. My plan is to create a slideshow effect using JavaScript. While I have implemented some functions, I must admit that it is not very organized at the moment. The main ...

Executing Javascript within an iframe

Is there a way to include a script in an iframe? I came up with the following solution: doc = $frame[0].contentDocument || $frame[0].contentWindow.document; $body = $("body", doc); $head = $("head", doc); $js = $("<script type='text/javascript&a ...

AJAX seems to be struggling to recognize JSON data as JSON format

I am facing an issue with my AJAX call where the data received from the server is not being treated as JSON, despite setting the datatype to json: function RetrieveMateriasFromServer(callback){ var status_aux; //HTTP request for data from the given UR ...

Is there a way to retrieve the list of files from a static public folder using javascript?

I have successfully set up a public folder directory using express and node. For instance, this code works perfectly - var testImage = new Image(); testImage.src = '/images/png/avatar.png'; However, I need to access several images stored ins ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Retrieve the modal ID when the anchor tag is clicked in order to open the modal using PHP

I am facing an issue with opening a modal and passing the id value using JavaScript. The id value is shown in a hidden input field. <a href="#modal2" data-toggle="modal" data-id="<?php echo $CRow['id'];?>" id="<?php echo $CRow[& ...

Guide to utilizing element reference with material UI components in Angular

I am facing difficulty in accessing the reference of an element. My intention is to wrap the material UI elements within a div and set the opacity: 0 so that it remains hidden in the HTML, allowing me to handle the value in my component.ts file. The main g ...

Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object: myObj: { foo: 1, bar: 2 } Within a component, I have a computed property set up like so: myObjVals: { get(){ return this.$store.state.myObj ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Displaying <p> content upon selection of a radio button

As a beginner in JS + HTML, I am looking to create 4 radio buttons with different names like this: o PS4 o Xbox o Nintendo DS When one of these is clicked/checked, I want to display the price which will be located in a "p" tag next to them, like so: o P ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

Rendering HTML with jQuery using AJAX: Step-by-step guide

Within my webpage, I have implemented a select box that contains a list of various books. The purpose of this select box is to allow the user to choose a book and then click a submit button in order to view the chapters of that book on a separate page. Ho ...