Skip to content

Instantly share code, notes, and snippets.

@shakhal
Created January 21, 2015 10:29
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 shakhal/3c7bd76179afeebd30f4 to your computer and use it in GitHub Desktop.
Save shakhal/3c7bd76179afeebd30f4 to your computer and use it in GitHub Desktop.
Yearly Quarters math, add, subtract, increase etc...
var Quarter = function(year, quarter){
this.year = year;
this.quarter = quarter;
this.str = function(){
return this.year+"_"+this.quarter;
}
this.increase = function(){
this.quarter += 1;
if(this.quarter > 3){
this.quarter = 0
this.year++
}
return this;
}
this.decrease = function(add){
this.quarter -= 1;
if(this.quarter < 0){
this.quarter = 3
this.year--
}
return this;
}
this.add = function(num){
this.quarter += num % 4;
this.year += Math.floor(num / 4);
if(this.quarter > 3){
this.quarter = this.quarter - 4
this.year++;
}
return this;
}
this.sub = function(num){
this.quarter -= num % 4;
this.year -= Math.floor(num / 4);
if(this.quarter < 0){
this.quarter = this.quarter + 4
this.year--;
}
return this;
}
/**
* Get previous quarters, including current, one based.
* @param numOfQuarters : quarter to start counting back from
* @return Array : [Quarter, ...]
*/
this.getLastQuarters = function (numOfQuarters){
var res = [];
var q = this.quarter;
for (var i = 0; i < numOfQuarters; i++) {
res.push(new Quarter(this.year, this.quarter).sub(i));
if (q == 1){
year--;
q = 4;
}
else{
q--;
}
};
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment