// 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