-
Notifications
You must be signed in to change notification settings - Fork 1
More idiomatic comparison methods #6
Description
Summary of discussion from tc39/proposal-temporal#1086 and meeting minutes:
The Temporal.(type).compare() static methods have confusing parameter order, in order for them to be able to be used as the comparator function for Array.prototype.sort().
A suggestion that's come up several times is that Temporal types could have more idiomatic methods named something like lessThan(), earlierThan(), isBefore(), isSameOrAfter(). Although these would duplicate the functionality of compare(), they would make user code much easier to read.
For example:
// proposed
function afterKidsBedtime(time) {
return time.greaterThan('20:30');
}
// current
function afterKidsBedtime(time) {
return Temporal.PlainTime.compare(time, '20:30') > 0;
}There was a work-in-progress at tc39/proposal-temporal#1074 on which a proposal in this repository can be based.
Sets of names that were proposed so far:
- greaterThan(), lessThan(), greaterEquals(), lessEquals()
- greater(), lesser(), greaterEquals(), lesserEquals()
- greater(), lesser(), greaterOrEquals(), lesserOrEquals()
- greater(), less(), greaterEquals(), lessEquals()
- greater(), less(), greaterOrEquals(), lessOrEquals()
- gt(), lt(), ge(), le()
- earlier(), later(), earlierEquals(), laterEquals()
Advantages:
The meaning of the return value of compare(a, b) has been confusing since it was first introduced in C, because you have to think carefully about whether 1 means a > b or b < a. It can't be read left-to-right.
An isSame() method could, in addition, implement equality based on the internal ISO-calendar slots of the Temporal object, without taking the calendar into account, which makes it fulfill a different function from equals().
Concerns:
Such an API might become useless if operator overloading is ever added to the language, at which point the comparison operators could simply be used.
Names like greaterThan() are closely tied to English grammar and so may only improve the issue for English speakers.
A problem with names implying "before" or "after" is that due to time zones, a wall-clock time that is "greater than" another wall-clock time may not actually be "after" it. These names also wouldn't be consistent if similar methods were added to Temporal.Duration.
Prior art:
- Moment (including the ability to specify the granularity:
isSame('day') - ThreeTen / java-time / js-joda:
time1.isAfter(time2) - TBD
Constraints / corner cases:
TBD