0
0

More than 1 year has passed since last update.

ジェネレーターとは

イテレーターを作ってみて思ってたのが
めんどくさい、、
もっと簡単な方法ないのか?
→ジェネレーターを使おう

書き方

1.functionの後に*をつける
2.関数名は gen()
3.yield 値 値を追加してから継続
4.return 値 値を追加してインクリメント終了
5.呼び方はイレテータと変わらない

ジェネレータのコード

function* gen(){
    yield 1;
    yield 2;
    yield 3;
    return 4;
}
const it =gen()
console.log(it.next())
console.log(it.next())
// 上限
console.log(it.next())
// 4回目の上限オーバー
console.log(it.next())

スクリーンショット 2022-09-07 15.28.18.png

イテレータだと

function genIterator(max){
	let i = 0;
	return{
  	next:function(){
    // ifで引数が上限に達した時,done:trueを返してあげましょう
    if(i > max){
    return{
    	done:true
    }
    }else{	    
      return{
        done:false,
        value: i++
       }
      }
    }
  }
}

whileと組み合わせる

function* gen(max=10){
 let i = 0
 while(i < max)  
   yield i++;
   
    return max;
}
const it =gen(4)

console.log(it.next())
console.log(it.next())
// 上限
console.log(it.next())
// 4回目の上限オーバー
console.log(it.next())
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0