Generator Functions की जानकारी
In this page:
function* name(): Generator<YieldType, ReturnType, NextType> {
yield value;
}
Basic Generators
एक generator function हर yield पर execution को pause करती है और सिर्फ तब resume होती है जब next फिर call हो — इसका return type Generator<TYield, TReturn, TNext> उस exchange में शामिल सभी तीन values describe कर सकता है।
उदाहरण: Basic Generators
function* countUp(): Generator<number, void, unknown> {
yield 1;
yield 2;
yield 3;
}
console.log([...countUp()]);
Generator Return Values
एक generator normally complete होने पर (generator body के अंदर एक return statement के through) एक final value return कर सकता है, और Generator का दूसरा type parameter exactly describe करता है कि वह return value किस type की है।
उदाहरण: Generator Return Values
function* gen(): Generator<number, string, unknown> {
yield 1;
yield 2;
return "done";
}
const it = gen();
console.log(it.next(), it.next(), it.next());
Passing Values to Generators
तीसरा Generator type parameter next(value) के through generator में pass की गई values के type describe करता है — ध्यान दें कि next की बिल्कुल पहली call generator को run करना शुरू करती है, इसलिए उस पहली call को pass किया गया कोई भी argument ignore हो जाता है।
उदाहरण: Passing Values to Generators
function* echo(): Generator<string, void, string> {
const input = yield "first";
console.log("Received:", input);
}
const it = echo();
console.log(it.next());
it.next("hello");
Generators for Data Processing
Generators sequences को lazily produce करने के लिए ideal हैं, यानी हर value सिर्फ तब compute होती है जब वह actually request की जाती है, बजाय पूरी array को पहले ही eagerly compute करने के।
उदाहरण: Generators for Data Processing
function* lazyRange(end: number): Generator<number> {
for (let i = 0; i < end; i++) yield i;
}
for (const n of lazyRange(3)) {
console.log(n);
}
Generators and Iterable
Generator objects automatically iterable protocol implement करते हैं, इसलिए उन्हें directly for...of से consume किया जा सकता है, एक array में spread किया जा सकता है, या destructure किया जा सकता है — कोई extra wiring ज़रूरी नहीं।
उदाहरण: Generators and Iterable
function* fruits(): Generator<string> {
yield "apple";
yield "banana";
}
console.log([...fruits()]);
const [first] = fruits();
console.log(first);
function* countUpमें*भूल जाना, इसलिएyieldएक syntax error बन जाता है।- यह उम्मीद करना कि पहला
next(value)argument receive होगा, जब यह discard हो जाता है क्योंकि generator अभी किसीyieldतक नहीं पहुंचा होता। - एक generator को दो बार iterate करना और दूसरी बार कुछ न मिलना, क्योंकि यह पहले से ही exhausted है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: