Reputation: 3157
In this simple code, the console.log(names.next().value);
if called twice the array index increases. I'm not sure how its doing that since I think it should always start with 0 so it should have returned the same value.
Can someone explain how it is doing that?
// Iterator Example
function nameIterator(names) {
let nextIndex = 0;
console.log(nextIndex);
return {
next: function() {
return nextIndex < names.length ? {
value: names[nextIndex++],
done: false
} : {
done: true
}
}
}
}
// Create an array of names
const namesArr = ['Brad', 'Sara', 'John'];
// Init iterator and pass in the names array
const names = nameIterator(namesArr);
console.log(names.next().value);
console.log(names.next().value);
console.log(names.next().value);
console.log(names.next());
Output:
Brad
Sara
John
Object : {done: true}
Upvotes: 0
Views: 91
Reputation: 33726
Every time you call the function next
, the index it's incremented by 1 ->
nextIndex++
.
You can pass a flag indicating you want the current index value as follow:
// Iterator Example
function nameIterator(names) {
let nextIndex = 0;
return {
next: function(current) {
let index;
if (current) {
index = (nextIndex < names.length ? nextIndex : names.length) - 1;
} else {
index = nextIndex++;
}
return index < names.length ? {
value: names[index],
done: false
} : {
done: true
}
}
}
}
// Create an array of names
const namesArr = ['Brad', 'Sara', 'John'];
// Init iterator and pass in the names array
const names = nameIterator(namesArr);
console.log(names.next().value);
console.log(names.next(true).value);
console.log(names.next(true).value);
console.log(names.next(true).value);
console.log(names.next().value);
console.log(names.next(true).value);
console.log(names.next().value);
console.log(names.next());
console.log(names.next(true).value);
console.log(names.next());
Upvotes: 1
Reputation: 932
This is because next()
uses nextIndex
property present in your nameIterator()
function.
next()
doesn't have a separate copy of nextIndex
property available to itself. So when you do nextIndex++
in your next()
method, it actually updates the nextIndex
that we have in nameIterator()
, and the next time you call next()
, you'll access this updated nextIndex
only.
Upvotes: 1
Reputation: 20944
It's because of the following line in the code.
names[nextIndex++]
This line selects the index in the names
value and then increases the value of nextIndex
with one, but only after it has selected the key. See it in the example below to see what it outputs.
let arr = [1, 2, 3];
let index = 0;
console.log(arr[index++]);
console.log(arr[index++]);
console.log(arr[index++]);
nextIndex
increments with every time you call the next()
method and keeps going until the nextIndex
value reaches a threshold.
Upvotes: 1