Skip to content

Commit

Permalink
Fix handling margin for whole months
Browse files Browse the repository at this point in the history
  • Loading branch information
Michiel ter Reehorst committed Jan 12, 2017
1 parent 01edfc6 commit 4f3aa1a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/previous-date-range.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ class PreviousDateRange {

const end = moment(this.date);

if (!this.whole) {
end.subtract(this.margin, 'day');
} else {
end.startOf(this.cleanMeasure)
.subtract(this.margin, 'day')
if (this.whole) {
end
.subtract(this.margin - 1, 'day')
.startOf(this.cleanMeasure)
.subtract(1, 'day')
.endOf(this.cleanMeasure);
} else {
end.subtract(this.margin, 'day');
}

end.endOf('day');
Expand All @@ -47,7 +49,10 @@ class PreviousDateRange {

get isToDate() { return /ToDate$/.test(this.measure); }

get whole() { return this.WHOLE != null ? this.WHOLE : !this.isToDate; }
// Days are always whole days.
// If something is `<measure>ToDate`, then it isn't whole by default.
// Can be manually overruled for things that aren't a day.
get whole() { return this.cleanMeasure === 'day' || this.WHOLE != null ? this.WHOLE : !this.isToDate; }

get date() { return this.DATE; }

Expand All @@ -57,7 +62,7 @@ class PreviousDateRange {

get measure() { return this.MEASURE || 'month'; }

get cleanMeasure() { return this.measure.replace(/[s]?[ToDate]+$/, ''); }
get cleanMeasure() { return this.measure.replace(/[ToDate]+$/, '').replace(/s$/, ''); }

get countableMeasure() {
switch (this.cleanMeasure) {
Expand Down
12 changes: 12 additions & 0 deletions test/previous-date-range.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ describe('PreviousDateRange', function () {
expect(this.range.start.format(DAY_FORMAT)).to.equal('09-02-3000');
expect(this.range.end.format(DAY_FORMAT)).to.equal('10-02-3000');
});

it('should handle whole month', function () {
this.range.date = new Date(3000, 0, 1);

expect(this.range.start.format(DAY_FORMAT)).to.equal('01-12-2999');
expect(this.range.end.format(DAY_FORMAT)).to.equal('31-12-2999');

this.range.margin = 2;

expect(this.range.start.format(DAY_FORMAT)).to.equal('01-11-2999');
expect(this.range.end.format(DAY_FORMAT)).to.equal('30-11-2999');
});
});

describe('whole', function () {
Expand Down

0 comments on commit 4f3aa1a

Please sign in to comment.