Skip to content

Instantly share code, notes, and snippets.

@LeeeeeeM
Last active March 15, 2018 09:07
Show Gist options
  • Save LeeeeeeM/3d4412b585345a7715d666029298ac24 to your computer and use it in GitHub Desktop.
Save LeeeeeeM/3d4412b585345a7715d666029298ac24 to your computer and use it in GitHub Desktop.
实现迭代器
var util = {
isType: function(value, type) {
return Object.prototype.toString.call(value).toLowerCase().slice(8, -1) === type;
}
};
function Iterator(list) {
list = util.isType(list, 'array') ? list : [list];
this._array = list;
this._index = 0;
}
Iterator.prototype.next = function() {
return this._index < this._array.length ? {value: this._array[this._index++], done: false} : {value: undefined, done: true};
}
Iterator.prototype.map = function(fn) {
var newIterator = new Iterator(this._array);
var _self = this;
return {
next: function() {
var {done, value} = newIterator.next();
return {
done: done,
value: done ? undefined : fn.call(_self, value)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment