added useful number methods
#[no_std, cache_output]
+import 'string.spwn'
+extract import 'constants.spwn'
+
impl @number {
+ abs: #[desc("Returns the absolute value of the number") example("$.assert((-1).abs() == 1)")]
+ (self) -> @number => self if self >= 0 else -self,
+ round: #[desc("Returns the nearest integer to the number") example("$.assert((1.5).round() == 2)")]
+ (self) -> @number => $.round(self),
+ ceil: #[desc("Returns the smallest integer greater than or equal to the number") example("$.assert((1.5).ceil() == 2)")]
+ (self) -> @number => $.ceil(self),
+ floor: #[desc("Returns the largest integer less than or equal to the number") example("$.assert((1.5).floor() == 1)")]
+ (self) -> @number => $.floor(self),
+ sqrt: #[desc("Returns the square root of the number") example("$.assert(4.sqrt() == 2)")]
+ (self) -> @number => $.sqrt(self),
+ log: #[desc("Returns the logarithm of the number (default: natural logarithm)") example("$.assert(2.log() == 0.6931471805599453)")]
+ (self, base = EULER) -> @number => $.log(self, base),
+ lerp: #[desc("Returns the linear interpolation between the two numbers") example("$.assert((0.7).lerp(0,2) == 1.4")]
+ (self, lower, higher) -> @number => lower + (higher - lower) * self,
map: #[desc("Maps a number linearily from one interval to another") example("$.assert(2.map(1, 4, 5, 11) == 7)")]
(self, istart: @number, istop: @number, ostart: @number, ostop: @number) -> @number {
return ostart + (ostop - ostart) * ((self - istart) / (istop - istart))
@@ -13,10 +30,34 @@ impl @number {
(self, min: @number, max: @number) -> @number {
return ((self - min) % (max - min)) + min
},
- is_finite: #[desc("Checks if the number is finite") example("$.assert((0/0).is_finite()) == false")]
- (self) -> @bool {
- return self - self == 0
+ ordinal: #[desc("Returns the number in ordinal form") example("$.assert(1.ordinal() == '1st')")]
+ (self) -> @string {
+ number = self.floor()
+ numb_abs = number.abs()
+ return switch true {
+ ==(((numb_abs % 100) / 10).floor() == 1): "{}th",
+ ==(numb_abs % 10 == 1): "{}st",
+ ==(numb_abs % 10 == 2): "{}nd",
+ ==(numb_abs % 10 == 3): "{}rd",
+ else: "{}th",
+ }.fmt(number)
},
+ to_fixed: #[desc("Turns the number into a string with the given precision") example("$.assert(1.to_fixed(2) == '1.00')")]
+ (self, precision: @number = 0) -> @string {
+ let precision = precision.ceil()
+ let string = self as @string
+ let dot_index = string.index(".")
+ if dot_index == null {
+ dot_index = string.length
+ if string.length - dot_index + precision <= 0 { return string }
+ string += "."
+ }
+ string = string.r_pad(dot_index + precision + 1, "0")
+ string = string.substr(0, dot_index + precision + 1)
+ return string.r_trim(".") // hopefully chaining will be fixed soon
+ },
+ is_finite: #[desc("Checks if the number is finite") example("$.assert((0/0).is_finite()) == false")]
+ (self) -> @bool => self - self == 0,
}
