Created
January 21, 2015 10:29
-
-
Save shakhal/3c7bd76179afeebd30f4 to your computer and use it in GitHub Desktop.
Yearly Quarters math, add, subtract, increase etc...
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
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