diff --git a/src/function/builtin.rs b/src/function/builtin.rs index b4d6cab..1819439 100644 --- a/src/function/builtin.rs +++ b/src/function/builtin.rs @@ -121,6 +121,15 @@ pub fn builtin_function(identifier: &str) -> Option { Ok(Value::Float(max_float)) } })), + "if" => Some(Function::new(|argument| { + if let [condition, if_true, if_false] = &argument.as_fixed_len_tuple(3)?[..] { + return Ok(if condition.as_boolean()? { if_true } else { if_false }.clone()) + } + Err(EvalexprError::type_error( + argument.clone(), + vec![ValueType::Boolean, ValueType::Empty, ValueType::Empty], + )) + })), "len" => Some(Function::new(|argument| { if let Ok(subject) = argument.as_string() { Ok(Value::from(subject.len() as i64)) diff --git a/src/lib.rs b/src/lib.rs index 967a48c..e7cabaf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -327,6 +327,7 @@ //! | `floor` | 1 | Numeric | Returns the largest integer less than or equal to a number | //! | `round` | 1 | Numeric | Returns the nearest integer to a number. Rounds half-way cases away from 0.0 | //! | `ceil` | 1 | Numeric | Returns the smallest integer greater than or equal to a number | +//! | `if` | 3 | Boolean, Any, Any | If the first argument is true, returns the second argument, otherwise, return the third | //! | `math::ln` | 1 | Numeric | Returns the natural logarithm of the number | //! | `math::log` | 2 | Numeric, Numeric | Returns the logarithm of the number with respect to an arbitrary base | //! | `math::log2` | 1 | Numeric | Returns the base 2 logarithm of the number | diff --git a/tests/integration.rs b/tests/integration.rs index d93c235..cd7639b 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -408,6 +408,9 @@ fn test_builtin_functions() { assert_eq!(eval("shl(-6, 5)"), Ok(Value::Int(-192))); assert_eq!(eval("shr(5, 1)"), Ok(Value::Int(2))); assert_eq!(eval("shr(-6, 5)"), Ok(Value::Int(-1))); + assert_eq!(eval("if(true, -6, 5)"), Ok(Value::Int(-6))); + assert_eq!(eval("if(false, -6, 5)"), Ok(Value::Int(5))); + assert_eq!(eval("if(2-1==1, \"good\", 0)"), Ok(Value::String(String::from("good")))); } #[test]