What is the process through which Generator.next() works with its parameter?

According to the documentation, it mentions that "You can also provide a parameter to the next method to send a value to the generator." But where exactly does it send this value to?

Let's consider these 3 different generator functions:

function* first() {
  while(true) {
    var value = yield null;
  }
}
var g1 = first();  g1.next();
g1.next(1000); // yields null

function* second() {
  var i = 0;
  while (true) {
    i += yield i;
  }
}
var g2 = second(); g2.next(); 
g2.next(1000) // yields 1000

function* third(){
  var index = 0;
  while (true)
    yield index++;
}

 g3 = third();
 g3.next();
 g3.next(1000); // yields 1

In generators 3 and 1, it seems like the argument passed has no impact on the next method. Why is this the case? How does generator 2 calculate its return value? And why does it seem to be influenced by the provided argument?

Answer №1

To truly grasp this concept, it is crucial to understand how the subsequent function retrieves the argument provided to next(), which happens through the yield operator's return value:

[rv] = yield [expression];

Irrespective of [expression]'s value, when resuming execution from a prior iteration, yield will assign the value passed to next() to rv.

However, the catch is this: yield only assigns the value passed to next() during a continuation from a previous cycle. Therefore, during the initial iteration, yield does not assign anything to rv.

For instance, in a generator like the following:

function* gen() {
  // During the first iteration, yield does not produce any value.
  // It only returns something when execution is resumed.
  returnedFromYield = yield 'foo'; 
  yield returnedFromYield; 
}

During the first iteration, returnedFromYield remains undefined. It is only on the second iteration that yield assigns the provided value to returnedFromYield, which is then returned:

g.next(1); // 'foo'
g.next(2); // 2

Let's consider another scenario:

function* gen() {
  yield yield yield 5;
}

Upon the first iteration (g.next()), yield returns 5. On the subsequent iteration (g.next(10)), yield passes 10 to the second yield. Thus, yield yield yield 5; in the second iteration is akin to yield yield 10;, and on the third iteration, it is equivalent to yield valuePassedToNext.

Answer №2

Illustrated below is a detailed example demonstrating the logical progression and extent of the values passed to a generator's next method. The segment affected by the next method invocation is visibly marked in the designated color scheme.

https://i.sstatic.net/HrMk4.jpg

a: In the absence of a yield, the parameter 'one' is disregarded. The generator halts at line 5, delivering the value 1.

b: Subsequent execution results in 'two' taking the place of the yield on line 5, being assigned to the yieldValue variable. Line 6 is processed. The generator pauses at line 8, producing the value 2.

c: Continuation leads to 'three' supplanting the yield on line 8, and being stored in the yieldValue variable. Line 9 is executed. Pausing at line 11, the generator emits the value 3.

d: Proceeding with 'four' replacing the yield on line 11, and stored in the yieldValue variable. Line 12 is executed. Following that, line 14 is executed. As a final step, the generator completes, returning the value undefined.

Refer to the logs between line 28 and 36 for more information

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 is the best way to load a model and save it to a variable for future use?

One issue I'm facing involves loading a model in this manner: var Beech; var loader = new THREE.JSONLoader(); loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) { Beech = addMorphTree(geometry,materials,0.5); }); and uti ...

Remove the most recent row that was dynamically inserted into an HTML table

Currently, I am in the process of developing an ASP.NET Web Api 2.2 application using .NET Framework 4.5, C#, and jQuery. Within one of my views, I have set up the following table: <table id ="batchTable" class="order-list"> <thead> ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

React: Placing a value directly at the cursor

How can I dynamically insert a selected value from a dropdown into an input field at the position of the cursor? import { useState } from "react"; import "./styles.css"; export default function App() { const [cur, setCur] = useState( ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

The function of style.marginRight differs from that of style.marginLeft

One function aligns content to the left while the other doesn't align it to the right function openNavLeft() { document.getElementById("mySidenavLeft").style.width = "100vw"; document.getElementById("main").style.marginLeft = "100vw"; } function ...

Challenges with the jScroll Plugin

Trying to implement jScroll to load a partial view multiple times using an increasing page number. The partial view returns a few divs. To achieve infinite scrolling, the partial view needs to have a hyperlink tag that directs to the next page to load. Th ...

Leverage the power of Angular to seamlessly integrate jQuery code across your

Interested in incorporating the plugin into my AngularJS project. To achieve this, I have to: $(document).ready( function() { $("html").niceScroll(); } ); The challenge is figuring out where to place this code so that it runs site-wide and ...

What could be the reason my black overlay doesn't show up when the button is clicked?

Attempting to craft a pop-up window on my own, I encountered an issue. Upon pressing the button, instead of the anticipated pop-up appearing and darkening the background below it, the entire page freezes with no sign of the pop-up box. If I eliminate the ...

When large spheres meet, Three.js/WebGL displays them as fractured

I must admit that I am not very experienced with 3D graphics. Issue In my WebGL model using Three.js, I have intentionally made two spheres collide. However, when the spheres are extremely large, they appear "broken" at the point of intersection, whereas ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

Rendering Highcharts React Pie Chart Multiple Times

Here is the code snippet: import React, { useEffect, useRef, useState } from "react"; import * as Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; export const PieChart = (props: any) =&g ...

What is the process for converting x and y coordinates to align with a fixed display?

When I make an API call, I am receiving X and Y coordinates in the following format: x: "-0.0120956897735595703" y: "0.147876381874084473" To display these coordinates on my minimap images, I have set their display to be absolute. The "left" and "top" pr ...

Activate trust proxy in Next.js

When working with Express.js, the following code snippet enables trust in proxies: // see https://expressjs.com/en/guide/behind-proxies.html app.set('trust proxy', 1); I am attempting to implement a ratelimit using an Express middleware that is ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks! Please keep your response simple ...