Last active
July 11, 2018 07:46
-
-
Save naoxink/f9bba51a5210956d1d9a18732c39c675 to your computer and use it in GitHub Desktop.
Simple iterator in Javascript
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
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