How to invoke a generator function a second time with different parameters in JavaScript?

Is it possible to pass different parameters to a generator function when I call next()?

function *random (firstParameter, secondParameter = undefined, thirdParameter = undefined) {
  yield firstParameter
  yield secondParameter + thirdParameter
}

let arbitrary = random(1)
console.log(arbitrary.next()) // 1
console.log(arbitrary.next(undefined, 2, 3)) // Expected: 5, got: NaN

secondParameter and thirdParameter are not available at the first yield in my application.



First of all the it is meaningless to assign undefined as a default value to the function arguments. However the main problem is that, you can return only a single value with the .next() method of the iterator. So in order to perform this task purposefully you may do as follows;

function *random (firstParameter, secondParameter = undefined, thirdParameter = undefined) {
  [secondParameter,thirdParameter] = yield firstParameter;
  yield secondParameter + thirdParameter;
}

var arbitrary = random(1);
console.log(arbitrary.next().value); // 1
console.log(arbitrary.next([2,3]).value); // Expected: 5, got: 5

You can not change the generator while calling it.

Instead, you could get a new generator object by calling the generator function function * with other parameters.

function *random (firstParameter, secondParameter = undefined, thirdParameter = undefined) {
    yield firstParameter;
    yield secondParameter + thirdParameter;
}

let arbitrary = random(1);
console.log(arbitrary.next()); // 1
console.log(arbitrary.next()); // NaN

let arbitrary2 = random(undefined, 2, 3);
console.log(arbitrary2.next()); // undefined
console.log(arbitrary2.next()); // 5

I didn’t really understand what you are trying to achieve. Without knowing what you want to do, I don’t really know if the structure of your generator is the correct one (and I don’t even know if you really need a generator).
But what about something like this?

function *random (firstParameter, secondParameter = undefined, thirdParameter = undefined) {
  yield firstParameter
  yield secondParameter + thirdParameter
}

let arbitrary = random(1, 2, 3);
console.log(arbitrary.next()); // 1
console.log(arbitrary.next()); // 5
console.log(arbitrary.next()); // undefined

EDITED: If you don’t have your other parameters available immediately, you need to instantiate again your generator. You instance your generator at the beginning, and then you cannot change it. So you may do something like this: