Skip to content

Commit

Permalink
New compare for comparing Decimal128 objects as digit strings
Browse files Browse the repository at this point in the history
This operation models IEEE 754's `compare_total` operation.
  • Loading branch information
jessealama committed Apr 16, 2024
1 parent 9622781 commit 4df57cb
Show file tree
Hide file tree
Showing 3 changed files with 429 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
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 4df57cb

Please sign in to comment.