Skip to content

Instantly share code, notes, and snippets.

@dmitrykuznetsovdev
Last active December 1, 2016 10:45
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 dmitrykuznetsovdev/23f7104fa5d923b1358f0d48c6976701 to your computer and use it in GitHub Desktop.
Save dmitrykuznetsovdev/23f7104fa5d923b1358f0d48c6976701 to your computer and use it in GitHub Desktop.
Create loop
var aList = ['A','B','C','D','E'];
/**
*
* @param {Array} arr
* @return {Generator}
*/
function* cycle(arr) {
const arr = [...arr];
let i = 0;
while (true) {
i = (i + ((yield arr[i]) || 1)) % arr.length
}
}
let rCycle = cycle(aList);
console.log(rCycle);
console.log(rCycle.next());
console.log(rCycle.next());
console.log(rCycle.next(-1));
console.log(rCycle.next(2));
function looper( arr ){
arr.loop_idx = 0;
// return current item
arr.current = function(){
this.loop_idx = ( this.loop_idx ) % this.length;// no verification !!
return arr[ this.loop_idx ];
};
// increment loop_idx AND return new current
arr.next = function(){
this.loop_idx++;
return this.current();
};
// decrement loop_idx AND return new current
arr.prev = function(){
this.loop_idx += this.length - 1;
return this.current();
};
}
console.log(aList.current());// -> A
console.log(aList.next());// -> B
console.log(aList.next());// -> C
console.log(aList.next());// -> D
console.log(aList.next());// -> E
console.log(aList.next());// -> A
console.log(aList.pop()) ;// -> E
console.log(aList.prev());// -> D
console.log(aList.prev());// -> C
console.log(aList.prev());// -> B
console.log(aList.prev());// -> A
console.log(aList.prev());// -> D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment