mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 18:58:12 +00:00
LibJS: Add a modulo() function to represent the "x modulo y" notation
This *not* being the same as C++ "%" in all cases is a massive footgun, and hopefully one I came across for the last time.
This commit is contained in:
parent
e93ce1ff69
commit
3d84fb64c3
1 changed files with 14 additions and 0 deletions
|
@ -76,4 +76,18 @@ ThrowCompletionOr<T*> ordinary_create_from_constructor(GlobalObject& global_obje
|
|||
return global_object.heap().allocate<T>(global_object, forward<Args>(args)..., *prototype);
|
||||
}
|
||||
|
||||
// x modulo y, https://tc39.es/ecma262/#eqn-modulo
|
||||
template<typename T>
|
||||
T modulo(T x, T y)
|
||||
{
|
||||
// The notation “x modulo y” (y must be finite and non-zero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x - k = q × y for some integer q.
|
||||
VERIFY(y != 0);
|
||||
if constexpr (IsFloatingPoint<T>) {
|
||||
VERIFY(isfinite(y));
|
||||
return fmod(fmod(x, y) + y, y);
|
||||
} else {
|
||||
return ((x % y) + y) % y;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue