Created
August 28, 2012 00:18
-
-
Save trev/3493710 to your computer and use it in GitHub Desktop.
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
// This modified snippet is from a function that accepts the current month(currentmonth) and period(period) and adds the period to the current month and lists every month within the new period. It can accept negative or positive periods. | |
function iterveningMonths(year, month, period) { | |
var movement = period < 0 ? -1 : 1; //Which way are we going? | |
var out = []; | |
var result; | |
for (var i = Math.abs(period); i !== 0; i--) { | |
month += movement; //Increment or decrement month | |
result = month % 12; //Check to see where that month is on a 12 month[0..11] period | |
year = result === 0 ? year+movement : year; //Track the year while we're at it | |
out.push(result < 0 ? year + "-" + (result + 12) : year + "-" + result); //Push result to end of array | |
} | |
return out; | |
} | |
console.log(iterveningMonths(2012, 3, -50)); |
Love it, thanks!
Actually, @Benvie, it didn't work very well as it didn't handle negative periods very well nor did it loop properly.
If you apply a negative period, say -3 to a starting month being 1. You should get [0,11,12[ and not [1,0,1]
I still used some of the principles in your code snippet though. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
function iterveningMonths(start, end){
var movement = start > end ? -1 : 1;
var out = [];
for (var current = start; current !== end; current += movement) {
out.push(current % 12);
}
return out;
}
console.log(iterveningMonths(1, 20))