From a7968125569c01479b67c090869d62c9b5d4ad65 Mon Sep 17 00:00:00 2001 From: Daniel Bulant Date: Sat, 5 Aug 2023 21:51:55 +0200 Subject: [PATCH] add length native function --- src/nativeFunctions.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/nativeFunctions.rs b/src/nativeFunctions.rs index 20c8908..9a8c03c 100644 --- a/src/nativeFunctions.rs +++ b/src/nativeFunctions.rs @@ -131,5 +131,32 @@ pub fn get_native_functions() -> HashMap { func: rush_typeof }); + fn rush_length(_ctx: &mut Context, args: Vec) -> Result { + if args.len() != 1 { + return Ok(Variable::I64(args.len() as i64)); + } + let arg = args.get(0).unwrap(); + let res = match arg { + Variable::String(s) => s.len(), + Variable::Array(a) => a.len(), + Variable::HMap(h) => h.len(), + _ => bail!("Unsupported type") + }; + Ok(Variable::I64(res as i64)) + } + map.insert("length".to_string(), NativeFunction { + name: "length".to_string(), + description: "Returns the length of a string, array or hashmap".to_string(), + args: vec![String::from("var")], + func: rush_length + }); + + map.insert("$length".to_string(), NativeFunction { + name: "$length".to_string(), + description: "Returns the length of a string, array or hashmap".to_string(), + args: vec![String::from("var")], + func: rush_length + }); + map } \ No newline at end of file