From b693dc4684d55772fd76150c8f182fa474f2ff67 Mon Sep 17 00:00:00 2001 From: Mattias Wadman Date: Mon, 11 Nov 2024 19:37:18 +0100 Subject: [PATCH] Add reminder op for floats --- jaq-json/src/lib.rs | 7 ++++++- jaq-json/tests/funs.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/jaq-json/src/lib.rs b/jaq-json/src/lib.rs index 6acaeb402..f5df469c0 100644 --- a/jaq-json/src/lib.rs +++ b/jaq-json/src/lib.rs @@ -765,9 +765,14 @@ impl core::ops::Div for Val { impl core::ops::Rem for Val { type Output = ValR; fn rem(self, rhs: Self) -> Self::Output { - use Val::Int; + use Val::{Float, Int, Num}; match (self, rhs) { (Int(x), Int(y)) if y != 0 => Ok(Int(x % y)), + (Float(f), Int(i)) if i != 0 => Ok(Float(f % i as f64)), + (Int(i), Float(f)) if f != 0.0 => Ok(Float(i as f64 % f)), + (Float(x), Float(y)) if y != 0.0 => Ok(Float(x % y )), + (Num(n), r) => Self::from_dec_str(&n) % r, + (l, Num(n)) => l % Self::from_dec_str(&n), (l, r) => Err(Error::math(l, ops::Math::Rem, r)), } } diff --git a/jaq-json/tests/funs.rs b/jaq-json/tests/funs.rs index bf94ad901..3d1536aed 100644 --- a/jaq-json/tests/funs.rs +++ b/jaq-json/tests/funs.rs @@ -77,3 +77,46 @@ fn tojson() { give(json!(0), "0.0 / 0.0 | tojson", json!("null")); give(json!(0), "1.0 / 0.0 | tojson", json!("null")); } + +yields!( + math_rem, + "def f: -2, -1, 0, 2.1, 3, 4000000001; [f as $a | f as $b | try ($a % $b) catch .]", + json!([ + 0, + 0, + "cannot calculate -2 % 0", + -2.0, + -2, + -2, + -1, + 0, + "cannot calculate -1 % 0", + -1.0, + -1, + -1, + 0, + 0, + "cannot calculate 0 % 0", + 0.0, + 0, + 0, + 0.10000000000000009, + 0.10000000000000009, + "cannot calculate 2.1 % 0", + 0.0, + 2.1, + 2.1, + 1, + 0, + "cannot calculate 3 % 0", + 0.8999999999999999, + 0, + 3, + 1, + 0, + "cannot calculate 4000000001 % 0", + 0.49999983082315813, + 2, + 0 + ]) +);