Generator

در جاوااسکریپت، Generator نوع خاصی از تابع هست که می‌تونه اجرای خودش رو متوقف کنه و بعداً دوباره از همون نقطه ادامه بده.
این ویژگی با استفاده از کلمه کلیدی function* و دستور yield پیاده‌سازی میشه.

🔹 ساختار Generator

function* generatorFunction() { yield "Hello"; yield "World"; }
  • function* → تعریف تابع Generator

  • yield → مقدار رو برمی‌گردونه و اجرای تابع رو متوقف می‌کنه

🔹 استفاده از Generator

function* myGenerator() { yield 1; yield 2; yield 3; } const gen = myGenerator(); console.log(gen.next()); console.log(gen.next()); console.log(gen.next()); console.log(gen.next());

📌 خروجی:

{ value: 1, done: false } { value: 2, done: false } { value: 3, done: false } { value: undefined, done: true }

🔹 پیمایش Generator با for...of

function* colors() { yield "red"; yield "green"; yield "blue"; } for (let color of colors()) { console.log(color); }

📌 خروجی:

red green blue

🔹 مثال کاربردی (تولید بی‌نهایت اعداد)

function* infiniteNumbers() { let num = 1; while (true) { yield num++; } } const numbers = infiniteNumbers(); console.log(numbers.next().value); // 1 console.log(numbers.next().value); // 2 console.log(numbers.next().value); // 3

🔹 فرق Generator با Iterator

  • Iterator → باید دستی next() رو پیاده‌سازی کنیم.

  • Generator → خودش به صورت خودکار یک Iterator می‌سازه و کار رو راحت می‌کنه.

✅ خلاصه

  • Generatorها با function* تعریف میشن.

  • با yield میشه مقدارها رو مرحله‌به‌مرحله برگردوند.

  • Generatorها در واقع Iteratorهای ساده‌شده هستن.

  • میشه از for...of برای پیمایش Generator استفاده کرد.