JavaScript doesn’t support operator overloading, so I don’t think you’ll be able to find a solution that allows you to literally use +
and -
with composite year/month values.
However, you could define your own year/month object type with add and subtract methods:
function YearsMonths(years, months) {
this.years = years;
if (months > 11) {
this.years = this.years += Math.floor(months/12);
this.months = months % 12;
}
else {
if (months < 0) {
this.months = 12 + (months % -12);
this.years -= (Math.floor(months/-12) + 1);
}
else {
this.months = months;
}
}
}
YearsMonths.prototype.add = function (otherYearsMonths) {
newYears = this.years + otherYearsMonths.years;
newMonths = this.months + otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
YearsMonths.prototype.subtract = function (otherYearsMonths) {
var newYears = this.years - otherYearsMonths.years,
newMonths = this.months - otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
And then use it like this:
value1 = new YearsMonths(65, 0);
value2 = new YearsMonths(47, 9);
value3 = value1.subtract(value2);
value4 = value1.add(value2);
value3.years;
# 17
value3.months;
# 3
value4.years;
# 112
value4.months;
# 9