Skip to content

Commit

Permalink
New compare for comparing Decimal128 objects as digit strings (#105)
Browse files Browse the repository at this point in the history
* New `compare` for comparing Decimal128 objects as digit strings

This operation models IEEE 754's `compare_total` operation.

* Document less-than, equals, and compare
  • Loading branch information
jessealama authored Apr 16, 2024
1 parent 9622781 commit 2b07262
Show file tree
Hide file tree
Showing 4 changed files with 431 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [12.3.0] - 2024-04-16

### Added

- `compare` method for comparting Decimal128 objects as digit strings, not as mathematical values (models IEEE 754's `compare_total` operation)

## [12.2.0] - 2024-04-15

### Changed
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ This library is a prototype for the [decimal proposal](https://github.com/tc39/p
- remainder (`remainder`)
- rounding (`round`)
- `toString` emitting both decimal and exponential syntax (default is decimal)
- less-than (`lessThan`) and equals (`equals`) to compare by mathematical value
- `compare` for comparing Decimals as digit strings (e.g. `1.2` < `1.20`)

## Comparisons

Expand Down
68 changes: 68 additions & 0 deletions src/decimal128.mts
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,74 @@ export class Decimal128 {
return rationalThis.cmp(rationalX);
}

/**
* Compare two values. Return
*
* + -1 if this value is strictly less than the other,
* + 0 if they are equal, and
* + 1 otherwise.
*
* @param x
*/
compare(x: Decimal128): -1 | 0 | 1 {
if (this.isNaN) {
if (x.isNaN) {
return 0;
}
return 1;
}

if (x.isNaN) {
return -1;
}

if (!this.isFinite) {
if (!x.isFinite) {
if (this.isNegative === x.isNegative) {
return 0;
}

return this.isNegative ? -1 : 1;
}

if (this.isNegative) {
return -1;
}

return 1;
}

if (!x.isFinite) {
return x.isNegative ? 1 : -1;
}

if (this.isNegative && !x.isNegative) {
return -1;
}

if (x.isNegative && !this.isNegative) {
return 1;
}

if (this.lessThan(x)) {
return -1;
}

if (x.lessThan(this)) {
return 1;
}

if (this.exponent < x.exponent) {
return -1;
}

if (this.exponent > x.exponent) {
return 1;
}

return 0;
}

lessThan(x: Decimal128): boolean {
return this.cmp(x) === -1;
}
Expand Down
Loading

0 comments on commit 2b07262

Please sign in to comment.