構文解析する際に、文字列イテレート中に戻したりスキップしたりできるイテレータがあれば便利かと思い作ってみました。
参考: 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
!