Created
May 3, 2024 06:56
-
-
Save filiph/2f1deca67a28af32c052860078e6f86a to your computer and use it in GitHub Desktop.
An idea for an extension type for normalized floating point values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// A value that is guaranteed to be normalized (between `0.0` and `1.0`). | |
/// | |
/// Might be useful to avoid confusion in math-heavy code. | |
/// For example, a function might expect some of its arguments | |
/// to be normalized real numbers. Instead of just documenting | |
/// it in API docs or checking it at runtime, we can express it | |
/// through the parameter's static type. | |
/// | |
/// This is an extension type. The nice thing about those is that | |
/// they have zero runtime overhead. | |
extension type NormalizedDouble._(double value) implements double { | |
NormalizedDouble(double value) | |
: assert(value >= 0), | |
assert(value <= 1), | |
value = value.clamp(0, 1); | |
} | |
extension AsNormalizedDoubleExtension on double { | |
/// Asserts that this [double] is a normalized value | |
/// (between `0.0` and `1.0`). | |
/// | |
/// This does _not_ check whether the value is really normalized. | |
/// You would normally use this just after a computation. | |
NormalizedDouble get asNormalizedDouble => NormalizedDouble._(this); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment