For a recent talk I examined some native JavaScript functions in Node, and ended
up reading the source code for Math.max:
extern macro Float64Max(float64, float64): float64;
transitioning javascript builtin MathMax(
js-implicit context: NativeContext)(...arguments): Number {
let result: float64 = MINUS_V8_INFINITY;
const argCount = arguments.length;
for (let i: intptr = 0; i < argCount; i++) {
const doubleValue = TruncateTaggedToFloat64(arguments[i]);
result = Float64Max(result, doubleValue);
}
return Convert<Number>(result);
}
To better understand this function, I decided to write my own version in JavaScript:
class MyMath {
static max(...args) {
let result = -Infinity;
for (const value of args) {
result = value > result ? value : result;
}
return result;
}
}
It works as expected. And it even preserves Math.max()’s negative infinity
return when no argument is passed. Now I know why it does that; it’s the
result’s default value.
MyMath.max(100, 1); // 100
MyMath.max(); // -Infinity
Math.maxsource – Node V8