Retrieve data from a JavaScript generator-stream by applying a filter to the values

After watching a thought-provoking video on computerphile, I was inspired to try my hand at implementing the sieve algorithm using JavaScript generators. While I have experience with JavaScript, working directly with generators is a new challenge for me.

Here's my current progress:

function* nextNaturalNumber(n) {
    yield n;
    yield* nextNaturalNumber(n + 1);
}   

function* sieve(n) {
    let count = 0;
    let g = nextNaturalNumber(2);
    while (count++ < n) {
        const possiblePrime = g.next().value;
        yield possiblePrime;
        // Here's where I'm encountering an obstacle:
        // How can I filter out values from the nextNaturalNumber-generator stream that are not divisible by 2?
    }
}

// Display the first 10 prime numbers
for (const prime of sieve(10)) {
    console.log(prime);
}

The code-comment indicates my struggle with filtering out values in the generator stream that are not divisible by 2 and achieving the "sieve" operation. Is there a straightforward way to accomplish this task in JavaScript, similar to how it's done in Python with

yield from sieve(i for i in s if i%n !=0)
?

Answer №1

Regrettably, the Javascript language lacks robust iterator operations. One workaround is to create a filter function that iterates through the elements and returns only those that meet certain criteria:

function* generateSequence(n) {
    // Using iteration instead of recursion to prevent stack overflow
    while(true) {
        yield n;
        n++;
    }
}   

function* filterIterator(iterator, condition) {
    for (const item of iterator) {
        if (condition(item)) {
            yield item;
        }
    }
}

function* primeSieve(limit) {
    let count = 0;
    let sequence = generateSequence(2);
    while (count++ < limit) {
        const possiblePrime = sequence.next().value;
        yield possiblePrime;
        sequence = filterIterator(sequence, value => value % possiblePrime !== 0);
    }
}

// Display the first 10 prime numbers
for (const primeNumber of primeSieve(10)) {
    console.log(primeNumber);
}

Answer №2

Utilize the following code snippet to extract only odd values from your stream:

do {
    val = g.next().value;
} while (!(val%2));

Feel free to experiment with this functionality in your own code:

function* nextNaturalNumber(n) {
    yield n;
    yield* nextNaturalNumber(n + 1);
}   

function* sieve(n) {
    let count = 0;
    let g = nextNaturalNumber(2);
    while (count++ < n) {
       let val;
       do {
             val = g.next().value;
        } while (!(val%2));
        
        const possiblePrime=val;
        yield possiblePrime;
    }
}

// display the first 10 prime numbers
for (const prime of sieve(10)) {
    console.log(prime);
}

Answer №3

It concerns me that you may be leaning towards Pythonic coding in JavaScript, which might not always be the best approach. JavaScript favors explicit declaration of variables over hiding them in the stack like Python does. Consider this alternative:

//
// To iterate through natural numbers...
//
function* nextNaturalNumber(n) {
    while(true) {
        yield n;
        n++;
    }
}   

function* sieve() {
    //
    // Keep track of previously seen primes
    //
    let previousPrimes = [];
    for (const possiblePrime of nextNaturalNumber(2)) {
        //
        // Check if number is divisible by any previous prime
        //
        if (!previousPrimes.find((test) => (possiblePrime % test === 0))) {
            //
            // Return prime and add it to list of seen primes
            //
            yield possiblePrime;
            previousPrimes.push(possiblePrime);
        }
    }
}

let generator = sieve();
for(let i = 0; i < 10; i++) {
    console.log(generator.next().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

Navigate through the DOM to return an image

I have a question about clicking on the image '.escape' and passing back the source of the image '.myimg2' when clicked. Here is my attempt at accomplishing this task: I understand that it involves traversing the DOM, but I am not very ...

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

JavaScript function is not being invoked when receiving PHP arguments

When using the < a > tag in php, I encountered an issue where passing an argument in a JavaScript function did not result in the function being called. However, if I passed empty arguments, the function was executed. Here is the JavaScript code: fu ...

Sharing Angular 4 components in my project - collaboration at its finest

I have been working on an Angular project that consists of a variety of UI components. I would like to make these components available for use in other Angular projects and share them within the npm community. All of the components are located in a shared ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Loading data from external URLs using AJAX and JSON

I am facing an issue, can someone please help? I have two websites and I want to send data between them. First website: var site_adres = $(location).attr('href'); var myArray = site_adres.split('/'); var site_adi_al = myArray[2]; ...

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

Angular directive: Exploring the disparities between controller scope and link function scope

As I delve into the world of Angular directives, the concept of scope is proving to be quite challenging for me. Let's consider a custom directive named parentDirective, which has both a controller property and a link property: angular.module("app"). ...

Fade out a GLTF model in an A-frame after a short period of time

I'm trying to figure out how I can make my gltf model fade out after approximately 3 seconds using A-frame (https://aframe.io). I'm not sure about the best approach for this. Here is a snippet of my current code: <script> AFRAME.registerCom ...

Is it possible to utilize router.push within Redux thunk? Is this considered a beneficial approach?

I have this anchor element: <a className="btn btn-sm btn-circle" href={`https://www.facebook.com/sharer/sharer.php?u=${ process.env.NEXT_PUBLIC_ENVIRONMENT == "prod" ? "https://tikex.com" : "https:/ ...

Enhance the appearance of your custom Component in React Native by applying styles to Styled Components

I have a JavaScript file named button.js: import React from "react"; import styled from "styled-components"; const StyledButton = styled.TouchableOpacity` border: 1px solid #fff; border-radius: 10px; padding-horizontal: 10px; padding-vertical: 5p ...

Learn the technique of rotating a line around its endpoint using DragControls in three.js

I made a custom modification to DragControls.js so that it only allows movement of the line on the y-axis. Here is the line setup I am using: material = new THREE.LineBasicMaterial( { color: 0xFF0000 } ); geometry.vertices.push(new THREE.Vector3( 0, 0, 0 ...

Arranging information within an ExpansionPanelSummary component in React Material-UI

https://i.stack.imgur.com/J0UyZ.png It seems pretty clear from the image provided. I've got two ExpansionPanelSummary components and I want to shift the icons in the first one to the right, next to ExpandMoreIcon. I've been playing around with C ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Placing an eye icon on the password input field for optimal visibility and positioning

I am currently working on a Node.js project and I am attempting to incorporate an eye icon using Bootstrap into the password input field for visibility. Below is the code snippet of my input field: <div class="container"> <form ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

Passing an ID via Link to retrieve data with getServerSideProps in Next.js

I have several alert components. From each of these components, I aim to pass the itm._id and receive it in [itm].jsx within the same folder. In [itm].jsx, I intend to utilize it in the getServerSideProps function for fetching data. Below is a snippet fro ...

What is the best way to trigger a refresh of a cached CSS file on a JSP website, without using PHP?

I am currently making significant changes to my site by modifying a CSS file. Is there a way to compel clients to refresh the CSS in order to see the new updates? Unfortunately, it is not feasible to ask thousands of people to manually reload the page us ...

Sending data from JavaScript to Jade templatesIs this alright?

Utilizing node.js, express, jade, and socket.io, I have successfully executed JavaScript code on the jade side. However, I am encountering difficulty in generating HTML output from the script block. Based on your feedback, I have updated my question to in ...