Last active
June 11, 2017 02:29
-
-
Save gouf/4c86da9888bc0217f12515f7dece3c5b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Define functions | |
upDownCycleNumber = function(cycleLength) { | |
// Setup function | |
// Create an array like: | |
// [0, 1, 2, 3, 4, 5, 4, 3, 2, 1] | |
createUpDownCyclesArray = function(cycleLength) { | |
// Create an array like: | |
// [0, 1, 2, 3, 4, 5] | |
incrementalArray = | |
Array.apply(null, Array(cycleLength + 1)) | |
.map(function(_, i) { return i }) | |
// Create an array like: | |
// [0, 1, 2, 3, 4, 5] => [4, 3, 2, 1] | |
decrementalArray = | |
(function(incrementalArray){ | |
decrementalArray = incrementalArray.slice().reverse() | |
decrementalArray.shift() | |
decrementalArray.pop() | |
return decrementalArray | |
})(incrementalArray) | |
return incrementalArray.concat(decrementalArray) | |
} | |
self = this // for refer outer context of `this` from inner context | |
this.cycleValues = createUpDownCyclesArray(cycleLength) | |
this.index = 0 | |
// Closure function | |
return function() { | |
return self.cycleValues[self.index++ % self.cycleValues.length] | |
} | |
} | |
cycleLength = 5 | |
cycleValues = new upDownCycleNumber(cycleLength) | |
for(i = 0; i < 20; i++) { | |
console.log(cycleValues()) | |
} | |
// => | |
// 0 | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 | |
// 4 | |
// 3 | |
// 2 | |
// 1 | |
// 0 | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 | |
// 4 | |
// 3 | |
// 2 | |
// 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment