Skip to content

Commit

Permalink
feat(filters): Add sort_natural
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed May 17, 2017
1 parent 98a9565 commit ef14f87
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit ef14f87

Please sign in to comment.