I need to implement an algorithm with backtracking. For that I need to store an iterator value somehow, and restore it when I need to backtrack.
But I see no other way but to convert Maps and Sets into Arrays.
And I can see IteratorIndex
SetIterator {1, 2}
[[Entries]]
0: 1
1: 2
__proto__: Set Iterator
[[IteratorHasMore]]: true
[[IteratorIndex]]: 0
[[IteratorKind]]: "values"
in the console, but do not know how to access it.
I need something like this:
function f1(iter) {
// ...
iter.next()
// ...
const error = true
return ! error
}
function f2(iter) {
// ...
iter.next()
// ...
const error = false
return ! error
}
function f0(iter) {
const current_iter = iter
// trying to remember iterator's current position
// it doesn't work, obviously. Instead I need something like
// const current_iter = iter.copy()
if( f1(iter) ) return true
// f1() returns with an error, I need to backtrack
iter = current_iter
// trying to restore iterator's position after it was moved inside of f1()
if( f2(iter) ) return true
return false
}
const data = new Set([1,2,3,4])
const iter = data.values()
// ...
iter.next() // iterator is moved somewhere
// ...
f0(iter)
console.log(iter.next().value) // should be 3 but it's 4
Am I missing something, or is there any good reason not to allow Iterators' copies in JS?