Skip to content

Instantly share code, notes, and snippets.

@trev
Created August 28, 2012 00:18
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 trev/3493710 to your computer and use it in GitHub Desktop.
Save trev/3493710 to your computer and use it in GitHub Desktop.
// 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));
Copy link

ghost commented Aug 28, 2012

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

@trev
Copy link
Author

trev commented Sep 1, 2012

Love it, thanks!

@trev
Copy link
Author

trev commented Sep 1, 2012

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