From 27e6271402773bfe057403f7c1b8b3acf36de305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan?= Date: Thu, 19 Oct 2023 12:27:00 +0200 Subject: [PATCH] Implement modulo for duration (#10745) # Description This PR adds the ability to use modulo with durations: ```nu (2min + 31sec) mod 20sec # 11sec ``` # User-Facing Changes Allows to use ` mod ` --- crates/nu-protocol/src/value/mod.rs | 7 +++++++ src/tests/test_math.rs | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/nu-protocol/src/value/mod.rs b/crates/nu-protocol/src/value/mod.rs index fd85ce9cf4..96617a91b4 100644 --- a/crates/nu-protocol/src/value/mod.rs +++ b/crates/nu-protocol/src/value/mod.rs @@ -3445,6 +3445,13 @@ impl Value { Err(ShellError::DivisionByZero { span: op }) } } + (Value::Duration { val: lhs, .. }, Value::Duration { val: rhs, .. }) => { + if *rhs != 0 { + Ok(Value::duration(lhs % rhs, span)) + } else { + Err(ShellError::DivisionByZero { span: op }) + } + } (Value::CustomValue { val: lhs, .. }, rhs) => { lhs.operation(span, Operator::Math(Math::Modulo), op, rhs) } diff --git a/src/tests/test_math.rs b/src/tests/test_math.rs index ee4d139e39..930742bb31 100644 --- a/src/tests/test_math.rs +++ b/src/tests/test_math.rs @@ -120,6 +120,14 @@ fn test_filesize_op() -> TestResult { run_test("-5kb + 4.5kb", "-500 B") } +#[test] +fn test_duration_op() -> TestResult { + run_test("4min + 20sec", "4min 20sec").unwrap(); + run_test("42sec * 2", "1min 24sec").unwrap(); + run_test("(3min + 14sec) / 2", "1min 37sec").unwrap(); + run_test("(4min + 20sec) mod 69sec", "53sec") +} + #[test] fn lt() -> TestResult { run_test("1 < 3", "true").unwrap();