LoginSignup
5
1

More than 3 years have passed since last update.

途中で戻したり進めたりできるイテレータ

Last updated at Posted at 2020-04-01

構文解析する際に、文字列イテレート中に戻したりスキップしたりできるイテレータがあれば便利かと思い作ってみました。
参考: https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Iterators_and_Generators

function iter(pattern) {
    let index = 0
    return {
        [Symbol.iterator]: function() {
            return this
        },
        next: function() {
            if (index < pattern.length) {
                return { value: pattern[index++], done: false }
            } else {
                return { done: true }
            }
        },
        fetch: function() {
            return pattern[index]
        },
        back: function() {
            index > 0 && index--
        },
        skip: function() {
            index++
        },
    }
}

実際に利用したコードは長くなってしまったので、ちょっと無理矢理な使用例を示します。

使用例
let it = iter("Helo!!!!!, world!")
for (let c of it) {
    console.log(c)                    // 'Hel'
    if (c === 'l') break
}
it.back()                             // back to 'l'
console.log(it.next().value)          // 'l'
console.log(it.next().value)          // 'o'
while (it.fetch() === '!') it.skip()  // skip '!'
for (let c of it) {
    console.log(c)                    // ', world!'
}
実行結果
H
e
l
l
o
,

w
o
r
l
d
!
5
1
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
5
1