Skip to content

Instantly share code, notes, and snippets.

@naoxink
Last active July 11, 2018 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoxink/f9bba51a5210956d1d9a18732c39c675 to your computer and use it in GitHub Desktop.
Save naoxink/f9bba51a5210956d1d9a18732c39c675 to your computer and use it in GitHub Desktop.
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