Skip to content

Instantly share code, notes, and snippets.

@naoxink naoxink/createIterator.js
Last active Jul 11, 2018

Embed
What would you like to do?
Simple iterator in Javascript
function createIterator(array){
var index = -1
var hasNext = function(){
return (index + 1) < array.length
}
var hasPrev = function(param){
return (index - 1) < array.length && (index - 1) > -1
}
var next = function(){
return array[++index]
}
var prev = function(){
return array[--index]
}
var first = function(){
return array[0]
}
var last = function(){
return array[array.length -1]
}
var length = function(){
return array.length
}
var reset = function(){
index = 0
}
var position = function(){
return index
}
var info = function(){
return {
'length': length(),
'position': position(),
'hasNext': hasNext(),
'hasPrev': hasPrev(),
'data': array,
'actualValue': array[index]
}
}
return {
hasNext,
hasPrev,
next,
prev,
first,
last,
length,
reset,
position,
info
}
}
var it = createIterator([ 1, 2, 3, 4, 5, 'seis' ])
it.hasNext() // true
it.hasPrev() // false
it.next() // 1
it.next() // 2
it.hasPrev() // true
it.prev() // 1
it.first() // 1
it.last() // seis
it.length() // 6
it.reset() // Establece el índice del iterador en 0
it.next() // 1
it.next() // 2
it.next() // 3
it.position() // 2
it.info()
// {
// 'length': 6,
// 'position': 3,
// 'hasNext': true,
// 'hasPrev': true,
// 'data': [1, 2, 3, 4, 5, 'seis'],
// 'actualValue': 4
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.