Skip to content

Suggestion: consistent balancing behavior for Duration's plus and minus methods #645

@justingrant

Description

@justingrant

Duration.prototype.minus supports balancing, but Duration.prototype.plus doesn't. The docs admit that including balance in minus is not strictly required:

The default is balanceConstrain mode. The balance mode is only provided for convenience

Why does only minus get "convenience"? This inconsistency seems unnecessary and will makes things harder for new users. Seems like either both methods should balance, or neither of them should.

One option would be to remove balancing from the options for all Duration methods (including with and from), and add a new balanced method to do the balancing. I think @sffc recommended adding this kind of method in another issue, but I can't find it at the moment.

Another option would be to add a balance option to plus so that all four Duration methods would have consistent behavior.

But I don't think that the current inconsistent state makes sense.

Note that if we provide negative durations (#558), then parallel behavior between plus and minus will be required regardless.

To illustrate the problem, here's a use-case: "adjust a meeting length by a signed number of minutes and return a balanced result"

function adjustByMinutes(duration, minutes) {
  if (minutes < 0) { 
    return duration.minus({minutes}, {disambiguation: 'balance'});
  } else {
    // expected: 
    // return duration.plus({minutes}, {disambiguation: 'balance'});

    // `minus ({}` is the shortest "chained" solution in current polyfill,
    // because `with` will throw if passed an empty object
    duration.plus({minutes}).minus({}, {disambiguation: 'balance'});

    // non-chained alternative
    // Temporal.Duration.from(duration.plus({minutes}), {disambiguation: 'balance'});
  }
}

Another challenge with the current behavior is that balancing for plus results is not discoverable via reading code or via IDE autocomplete.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions