77 lines
2.7 KiB
Plaintext

== Why is this an issue?
In JavaScript, a generator is a special type of function that can be paused and resumed during its execution. It allows you to define an iterative algorithm by writing a function that can maintain its internal state and produce a sequence of values over time.
Generators are defined using a function syntax with an asterisk ``++(*)++`` appended to the ``++function++`` keyword (``++function*++``). Within the generator function, you can use the ``++yield++`` keyword to produce a value and temporarily pause the execution of the function, returning that value to the consumer.
[source,javascript]
----
function* generate() {
yield 1;
yield 2;
yield 3;
}
----
This example defines a generator function named ``++generate++`` that produces a sequence of values: 1, 2, and 3.
Using a generator without the ``++yield++`` keyword can limit the usefulness and potential benefits of generators. When you use the ``++yield++`` keyword without providing a value, it creates a yield expression that pauses the execution of the generator function and returns ``++undefined++`` as the yielded value.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
function* range(start, end) {
while (start < end) {
yield; // Noncompliant: The generator yields undefined
start++;
}
}
----
Yielding without a value makes it harder for the generator consumer to understand the purpose or context of the yielded value. Instead, one should always provide an explicit value with ``++yield++`` (using `undefined` when that is the intention) to make the generated sequence more meaningful and informative.
[source,javascript,diff-id=1,diff-type=compliant]
----
function* range(start, end) {
while (start < end) {
yield start;
start++;
}
}
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator[Generator]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield[``++yield++``]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Add a "yield" statement to this generator.
=== Highlighting
``++function* xxx++``
'''
== Comments And Links
(visible only on this page)
=== on 5 Feb 2016, 15:52:49 Elena Vilchik wrote:
\[~ann.campbell.2] Could you add to description smth like "It even could be a bug in your problem as you your iterator produced by this generator function is always empty"?
And I would like to remove highlighting and specific message for return, I don't think it's worth that. Are you ok?
=== on 5 Feb 2016, 16:06:15 Ann Campbell wrote:
done [~elena.vilchik]
endif::env-github,rspecator-view[]