diff options
author | Linus Groh <mail@linusgroh.de> | 2021-11-07 20:48:38 +0000 |
---|---|---|
committer | Linus Groh <mail@linusgroh.de> | 2021-11-07 21:11:31 +0000 |
commit | 3d84fb64c3426fce69976fb93fb48d389a7390f3 (patch) | |
tree | 6a165354cff4fd398005bbbb388c97aa9b137759 | |
parent | e93ce1ff691678cb07f50170adcc975398cf86ff (diff) | |
download | serenity-3d84fb64c3426fce69976fb93fb48d389a7390f3.zip |
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.
-rw-r--r-- | Userland/Libraries/LibJS/Runtime/AbstractOperations.h | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h index a935932084..1f68721298 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h @@ -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; + } +} + } |