Skip to content

Instantly share code, notes, and snippets.

@JosmanPS
Last active July 12, 2016 05:22
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 JosmanPS/d0741e86befece83b28b25f5161a0c66 to your computer and use it in GitHub Desktop.
Save JosmanPS/d0741e86befece83b28b25f5161a0c66 to your computer and use it in GitHub Desktop.
Some javascript classes to create a list of categories from a range of dates by year, month or day.
DateCategorizer = class DateCategorizer {
constructor(category_period, initial_date, final_date) {
this.period = category_period;
this.initial = initial_date;
this.final = final_date;
this.categorizer = this.categorizer_factory();
this.categories = [];
this.update_categories();
}
categorizer_factory() {
if (this.period === 'day') {
return new DayCategorizer(this.initial, this.final)
} else if (this.period === 'month') {
return new MonthCategorizer(this.initial, this.final)
} else { // period === 'year'
return new YearCategorizer(this.initial, this.final)
}
}
update_categories() {
this.categories = this.categorizer.get_categories();
}
}
AbstractCategorizer = class AbstractCategorizer {
constructor(initial, final) {
this.initial = new Date(initial);
this.final = new Date(final);
this._categories = [];
this.update_categories();
}
// abstract method
update_categories() {
this._categories = [];
}
get_categories() {
return this._categories
}
clone(date) {
var tt = date.toString();
var copy = new Date(tt);
return copy
}
format(date) {
return date.toISOString().substring(0, 10);
}
}
DayCategorizer = class DayCategorizer extends AbstractCategorizer {
update_categories() {
var date = this.clone(this.initial);
var category = this.format(date);
var final = this.format(this.final);
while (category <= final) {
this._categories.push(category);
date.setDate(date.getDate() + 1);
var category = this.format(date);
}
}
}
MonthCategorizer = class DayCategorizer extends AbstractCategorizer {
update_categories() {
var date = this.clone(this.initial);
var category = this.format(date);
var final = this.format(this.final);
while (category <= final) {
this._categories.push(category);
date.setMonth(date.getMonth() + 1);
var category = this.format(date);
}
}
format(date) {
var date = super.format(date);
return date.substring(0,7)
}
}
YearCategorizer = class DayCategorizer extends AbstractCategorizer {
update_categories() {
var date = this.clone(this.initial);
var category = this.format(date);
var final = this.format(this.final);
while (category <= final) {
this._categories.push(category);
date.setFullYear(date.getFullYear() + 1);
var category = this.format(date);
}
}
format(date) {
var date = super.format(date);
return date.substring(0,4)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment