Last active
March 15, 2018 09:07
-
-
Save LeeeeeeM/3d4412b585345a7715d666029298ac24 to your computer and use it in GitHub Desktop.
实现迭代器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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