diff --git a/src/filters.rs b/src/filters.rs index 31ffa75b8..fd00a1f48 100644 --- a/src/filters.rs +++ b/src/filters.rs @@ -475,7 +475,22 @@ pub fn sort(input: &Value, args: &[Value]) -> FilterResult { Ok(Value::Array(sorted)) } -// TODO sort_natural +pub fn sort_natural(input: &Value, args: &[Value]) -> FilterResult { + try!(check_args_len(args, 0, 0)); + + // TODO optional property parameter + + let array = input + .as_array() + .ok_or_else(|| InvalidType("Array expected".to_owned()))?; + let mut sorted: Vec<_> = array + .iter() + .map(|v| (v.to_string().to_lowercase(), v.clone())) + .collect(); + sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(cmp::Ordering::Equal)); + let result = sorted.into_iter().map(|(_, v)| v).collect(); + Ok(Value::Array(result)) +} /// Removes any duplicate elements in an array. /// @@ -1286,6 +1301,22 @@ mod tests { assert_eq!(result.unwrap(), tos!("a,1,c")); } + #[test] + fn unit_sort() { + let input = &Array(vec![tos!("Z"), tos!("b"), tos!("c"), tos!("a")]); + let args = &[]; + let desired_result = Array(vec![tos!("Z"), tos!("a"), tos!("b"), tos!("c")]); + assert_eq!(unit!(sort, input, args), desired_result); + } + + #[test] + fn unit_sort_natural() { + let input = &Array(vec![tos!("Z"), tos!("b"), tos!("c"), tos!("a")]); + let args = &[]; + let desired_result = Array(vec![tos!("a"), tos!("b"), tos!("c"), tos!("Z")]); + assert_eq!(unit!(sort_natural, input, args), desired_result); + } + #[test] fn unit_last() { assert_eq!(unit!(last, diff --git a/src/main.rs b/src/main.rs index 02277087d..2969ec875 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,7 +43,7 @@ fn load_yaml(path: &path::Path) -> Result { } #[cfg(not(feature = "serde_yaml"))] -fn load_yaml(path: &path::Path) -> Result { +fn load_yaml(_path: &path::Path) -> Result { bail!("yaml is unsupported"); } @@ -54,7 +54,7 @@ fn load_json(path: &path::Path) -> Result { } #[cfg(not(feature = "serde_json"))] -fn load_json(path: &path::Path) -> Result { +fn load_json(_path: &path::Path) -> Result { bail!("json is unsupported"); } diff --git a/src/template.rs b/src/template.rs index e5597619c..549c780f7 100644 --- a/src/template.rs +++ b/src/template.rs @@ -43,6 +43,7 @@ impl Renderable for Template { context.maybe_add_filter("size", Box::new(filters::size)); context.maybe_add_filter("slice", Box::new(filters::slice)); context.maybe_add_filter("sort", Box::new(filters::sort)); + context.maybe_add_filter("sort_natural", Box::new(filters::sort_natural)); context.maybe_add_filter("split", Box::new(filters::split)); context.maybe_add_filter("strip", Box::new(filters::strip)); context.maybe_add_filter("strip_html", Box::new(filters::strip_html));