Skip to content
This repository has been archived by the owner on Jan 15, 2025. It is now read-only.

New compare for comparing Decimal128 objects as digit strings #105

Merged
merged 2 commits into from
Apr 16, 2024
Merged
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
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