LoginSignup
0
0

More than 1 year has passed since last update.

108.イテレーターを自分で作成してみる

Posted at

イテレーターを自分で作成してみる

イテレーターとは

反復操作を行うための『オブジェクト』の総称のこと
ここでいう反復は繰り返しの処理のこと

フロー

1.関数を作成 インクリメントに使う変数を宣言しておく

function genIterator(max){
	let i = 0;
}

2.nextで返す

return{
  	next:function(){
    //
}

3.以下を加える

    1.doneはtrueにするとこれ以上インクリメントを行わない
    2.バリューにインクリメント加えとく
return{
	 done:false,
      value: i++
   	 }

4.呼び出す

console.log(it.next())
console.log(it.next())
console.log(it.next())

結果
スクリーンショット 2022-09-07 12.44.27.png

1-5までのコード

function genIterator(max){
	let i = 0;
	return{
  	next:function(){
    return{
			done:false,
      value: i++
   	 }
    }
  }
}

console.log(it.next())
console.log(it.next())
console.log(it.next())

上限に達した時に起動させないようにするには

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

console.log(it.next())
console.log(it.next())
console.log(it.next())

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

*つまりdone:trueであればいくらイテレータを呼び出してもインクリメントを呼ばない

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