LoginSignup
0
0

ワンライナーなdo{}while()

Posted at

イテレータを使う

  • イテラブル(反復可能プロトコル)
    • @@iterator つまり [Symbol.iterator] がイテレータを返すメソッドである
  • イテレータ(イテレータプロトコル)
    • next がイテレータリザルトを返すメソッドである
  • イテレータリザルト
    • value が現在の値を表す
    • done が次の値を生成できないことを表す真偽値
      • trueのときvalueは無視される
({value:'hello',done:false});// イテレータリザルト
({
    next:()=>({value:'hello',done:false})
});// イテレータ (注:無限ループ)
({
    next:()=>({value:'hello',done:false}),
    [Symbol.iterable](){return this;}
});// イテラブル (注:無限ループ)
({
    [Symbol.iterable]:()=>({
        next:()=>({value:'hello',done:false})
    })
});// これもイテラブル (注:無限ループ) 勝手に@@iterableが挿入される?

// =*=*=

console.log([...{[Symbol.iterator]:_=>({next:_=>({value:Math.random(),done:Math.random()>.9})})}]);
// はこれと同等の処理
do{
    console.log(Math.random());
}while((!Math.random()>.9));

// つまり
()=>{let a=[];do a.push(hoge());while(fuga());return a;}
// は
()=>[...{[Symbol.iterator]:_=>({next:_=>({value:hoge(),done:!fuga()})})}];
// に置換可能

使い所があるのかないのか

参考文献:

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