# Javascript iterator solution

• Use ES 6 symbol iteration for array.

``````/**
* @constructor
* @param {Integer[][]} vec2d
*/
var Vector2D = function(vec2d) {
this.it = vec2d[Symbol.iterator]();
this.shift = 0;
this.row = this.it.next();
};

/**
* @this Vector2D
* @returns {boolean}
*/
Vector2D.prototype.hasNext = function() {
while (this.row.done === false && this.shift === this.row.value.length) {
this.row = this.it.next();
this.shift = 0;
}
return this.row.done === false;
};

/**
* @this Vector2D
* @returns {integer}
*/
Vector2D.prototype.next = function() {
return this.row.value[this.shift++];
};

/**
* Your Vector2D will be called like this:
* var i = new Vector2D(vec2d), a = [];
* while (i.hasNext()) a.push(i.next());
*/
``````

• @roneil_PMH Thanks a lot.
There is a followup on this one: implement remove() function to remove "CURRENT" (not the next) element from the input array. Let me know if you can do it. :)

• remove "CURREN

Assume there is a "cur" pointer pointing to the current element. There are two situations here:

1. remove current, then "cur" and "shift" move back one place
For example: cur point to 2, shift to 3;
-----1-----2-----3-----4-----5-----6-----
----------cur--shift
Then delete cur;
-----1-----3-----4-----5-----6-----
----cur--shift

2. remove current, then array move back one place
-----1-----2-----3-----4-----5-----6-----
----------cur--shift
Then delete cur;
-----1-----3-----4-----5-----6-----
----------cur--shift

Which one do you mean by remove current?

In C++, the second one is chosen.

``````int main(int argc, const char * argv[]) {
vector<int> array = {1,2,3,4,5,6};
vector<int>::iterator cur = array.begin() + 2, shift = array.begin() + 3;
array.erase(cur);
cout<<*cur<<' '<<*shift<<endl;
return 0;
}
``````

The output is

``````4 5
``````

Also, what situation will the remove() be called at? Does hasNext(), next() will always been called before remove() or just randomly call remove()?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.