Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Date range constructor automatically sorts start/end dates #201

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/moment-range.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export class DateRange {

this.start = s || s === 0 ? moment(s) : moment(-8640000000000000);
this.end = e || e === 0 ? moment(e) : moment(8640000000000000);

if (this.end.isBefore(this.start)) {
[this.start, this.end] = [this.end, this.start];
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem safe to me (e.g. developer calling this makes a typo).

Double-check: have we already considered throwing an error instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for discussing 😃

IMO the library should provide the core time functionality, and the user can easily change their application logic if they're expecting a reversed time range. We classify it as a period between two points in time, rather than a directional period.

Throwing an error isn't ideal because most of the time, the functions on a range behave identically regardless of the start or end. I would think that it's far more inconvenient to require application start/end checks or error handling when they likely aren't requiring reverse time ranges? But I see the issue (if it's not documented clearly) of users not understanding what's happening.

@gf3 do you think it's better to throw error or is it unnecessary?

}

adjacent(other) {
Expand Down
9 changes: 9 additions & 0 deletions lib/moment-range_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ describe('DateRange', function() {
expect(r.start.isSame(quarterStart)).to.be(true);
expect(r.end.isSame(quarterEnd)).to.be(true);
});

it('should automatically sort the range start and end date', function() {
const a = moment('2005-01-01');
const b = moment('2008-12-20');
const r = moment.range(b, a);

expect(r.start.isSame(a)).to.be(true);
expect(r.end.isSame(b)).to.be(true);
});
});

describe('#adjacent', function() {
Expand Down