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

Commit 4df57cb

Browse files
committed
New compare for comparing Decimal128 objects as digit strings
This operation models IEEE 754's `compare_total` operation.
1 parent 9622781 commit 4df57cb

File tree

3 files changed

+429
-0
lines changed

3 files changed

+429
-0
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [12.3.0] - 2024-04-16
11+
12+
### Added
13+
14+
- `compare` method for comparting Decimal128 objects as digit strings, not as mathematical values (models IEEE 754's `compare_total` operation)
15+
1016
## [12.2.0] - 2024-04-15
1117

1218
### Changed

src/decimal128.mts

+68
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,74 @@ export class Decimal128 {
11941194
return rationalThis.cmp(rationalX);
11951195
}
11961196

1197+
/**
1198+
* Compare two values. Return
1199+
*
1200+
* + -1 if this value is strictly less than the other,
1201+
* + 0 if they are equal, and
1202+
* + 1 otherwise.
1203+
*
1204+
* @param x
1205+
*/
1206+
compare(x: Decimal128): -1 | 0 | 1 {
1207+
if (this.isNaN) {
1208+
if (x.isNaN) {
1209+
return 0;
1210+
}
1211+
return 1;
1212+
}
1213+
1214+
if (x.isNaN) {
1215+
return -1;
1216+
}
1217+
1218+
if (!this.isFinite) {
1219+
if (!x.isFinite) {
1220+
if (this.isNegative === x.isNegative) {
1221+
return 0;
1222+
}
1223+
1224+
return this.isNegative ? -1 : 1;
1225+
}
1226+
1227+
if (this.isNegative) {
1228+
return -1;
1229+
}
1230+
1231+
return 1;
1232+
}
1233+
1234+
if (!x.isFinite) {
1235+
return x.isNegative ? 1 : -1;
1236+
}
1237+
1238+
if (this.isNegative && !x.isNegative) {
1239+
return -1;
1240+
}
1241+
1242+
if (x.isNegative && !this.isNegative) {
1243+
return 1;
1244+
}
1245+
1246+
if (this.lessThan(x)) {
1247+
return -1;
1248+
}
1249+
1250+
if (x.lessThan(this)) {
1251+
return 1;
1252+
}
1253+
1254+
if (this.exponent < x.exponent) {
1255+
return -1;
1256+
}
1257+
1258+
if (this.exponent > x.exponent) {
1259+
return 1;
1260+
}
1261+
1262+
return 0;
1263+
}
1264+
11971265
lessThan(x: Decimal128): boolean {
11981266
return this.cmp(x) === -1;
11991267
}

0 commit comments

Comments
 (0)