From ad0b79673e216842ec1e0165866bd9402d52b8ca Mon Sep 17 00:00:00 2001 From: Jonathan Turner Date: Fri, 24 May 2019 18:20:03 -0700 Subject: [PATCH] Add split command --- src/cli.rs | 1 + src/commands.rs | 1 + src/commands/split.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 src/commands/split.rs diff --git a/src/cli.rs b/src/cli.rs index ca644a03d0..0ec35c094f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -60,6 +60,7 @@ pub async fn cli() -> Result<(), Box> { ("skip", Arc::new(skip::skip)), ("first", Arc::new(take::take)), ("select", Arc::new(select::select)), + ("split", Arc::new(split::split)), ("reject", Arc::new(reject::reject)), ("to-array", Arc::new(to_array::to_array)), ("where", Arc::new(where_::r#where)), diff --git a/src/commands.rs b/src/commands.rs index d7f5d02dcb..b48af5b02f 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -8,6 +8,7 @@ crate mod reject; crate mod select; crate mod skip; crate mod sort_by; +crate mod split; crate mod take; crate mod to_array; crate mod view; diff --git a/src/commands/split.rs b/src/commands/split.rs new file mode 100644 index 0000000000..5246e6849c --- /dev/null +++ b/src/commands/split.rs @@ -0,0 +1,35 @@ +use crate::errors::ShellError; +use crate::object::Value; +use crate::prelude::*; + +// TODO: "Amount remaining" wrapper + +pub fn split(args: CommandArgs) -> Result { + //let splitter = args.args[0].as_string()?; + let input = args.input; + let args = args.args; + + Ok(input + .map(move |v| match v { + Value::Primitive(Primitive::String(s)) => { + let splitter = args[0].as_string().unwrap(); + let split_result: Vec<_> = s.split(&splitter).filter(|s| s.trim() != "").collect(); + + if split_result.len() == (args.len() - 1) { + let mut dict = crate::object::Dictionary::default(); + for (k, v) in split_result.iter().zip(args.iter().skip(1)) { + dict.add(v.as_string().unwrap(), Value::Primitive(Primitive::String(k.to_string()))); + } + ReturnValue::Value(Value::Object(dict)) + } else { + let mut dict = crate::object::Dictionary::default(); + for k in args.iter().skip(1) { + dict.add(k.as_string().unwrap().trim(), Value::Primitive(Primitive::String("".to_string()))); + } + ReturnValue::Value(Value::Object(dict)) + } + } + _ => ReturnValue::Value(Value::Object(crate::object::Dictionary::default())), + }) + .boxed()) +}