Num; add min, max and clamp

This commit is contained in:
ruby0x1
2020-12-03 13:18:13 -08:00
parent 38f50fe091
commit 8361217369
4 changed files with 52 additions and 0 deletions

View File

@ -116,6 +116,20 @@ The binary (base-2) logarithm of the number. Returns `nan` if the base is negati
The exponential `e` (Eulers number) raised to the number. This: `eⁿ`.
### **min**(other)
Returns the minimum value when comparing this number and `other`.
### **max**(other)
Returns the maximum value when comparing this number and `other`.
### **clamp**(min, max)
Clamps a number into the range of `min` and `max`. If this number is less than min,
`min` is returned. If bigger than `max`, `max` is returned. Otherwise, the number
itself is returned.
### **pow**(power)
Raises this number (the base) to `power`. Returns `nan` if the base is negative.

View File

@ -735,6 +735,29 @@ DEF_PRIMITIVE(num_atan2)
RETURN_NUM(atan2(AS_NUM(args[0]), AS_NUM(args[1])));
}
DEF_PRIMITIVE(num_min)
{
double value = AS_NUM(args[0]);
double other = AS_NUM(args[1]);
RETURN_NUM(value <= other ? value : other);
}
DEF_PRIMITIVE(num_max)
{
double value = AS_NUM(args[0]);
double other = AS_NUM(args[1]);
RETURN_NUM(value > other ? value : other);
}
DEF_PRIMITIVE(num_clamp)
{
double value = AS_NUM(args[0]);
double min = AS_NUM(args[1]);
double max = AS_NUM(args[2]);
double result = (value < min) ? min : ((value > max) ? max : value);
RETURN_NUM(result);
}
DEF_PRIMITIVE(num_pow)
{
RETURN_NUM(pow(AS_NUM(args[0]), AS_NUM(args[1])));
@ -1325,6 +1348,9 @@ void wrenInitializeCore(WrenVM* vm)
PRIMITIVE(vm->numClass, "floor", num_floor);
PRIMITIVE(vm->numClass, "-", num_negate);
PRIMITIVE(vm->numClass, "round", num_round);
PRIMITIVE(vm->numClass, "min(_)", num_min);
PRIMITIVE(vm->numClass, "max(_)", num_max);
PRIMITIVE(vm->numClass, "clamp(_,_)", num_clamp);
PRIMITIVE(vm->numClass, "sin", num_sin);
PRIMITIVE(vm->numClass, "sqrt", num_sqrt);
PRIMITIVE(vm->numClass, "tan", num_tan);

View File

@ -0,0 +1,7 @@
var num = 4
System.print(num.clamp(0, 10)) // expect: 4
System.print(num.clamp(0, 1)) // expect: 1
System.print(2.clamp(0, 1)) // expect: 1
System.print((-1).clamp(0, 1)) // expect: 0
System.print((-1).clamp(-20, 0)) // expect: -1

View File

@ -0,0 +1,5 @@
var num = 4
var num2 = 6
System.print(num.max(num2)) // expect: 6
System.print(num.min(num2)) // expect: 4