Skip to content

Allow sort filter to be case insensitive #967

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/content/docs/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,12 @@ or by age:
{{ people | sort(attribute="age") }}
```

The `case_sensitive` argument (default is true) can be used to control the order of strings.

```jinja2
{{ people | sort(attribute="name.1", case_sensitive=false) }}
```

#### unique
Removes duplicate items from an array. The `attribute` argument can be used to select items based on the values of an inner attribute. For strings, the `case_sensitive` argument (default is false) can be used to control the comparison.

Expand Down
20 changes: 19 additions & 1 deletion src/builtins/filters/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ pub fn sort(value: &Value, args: &HashMap<String, Value>) -> Result<Value> {
Error::msg(format!("attribute '{}' does not reference a field", attribute))
})?;

let mut strategy = get_sort_strategy_for_type(first)?;
let case_sensitive = match args.get("case_sensitive") {
Some(val) => try_get_value!("sort", "case_sensitive", bool, val),
None => true,
};

let mut strategy = get_sort_strategy_for_type(first, case_sensitive)?;
for v in &arr {
let key = dotted_pointer(v, &attribute).ok_or_else(|| {
Error::msg(format!("attribute '{}' does not reference a field", attribute))
Expand Down Expand Up @@ -451,6 +456,19 @@ mod tests {
);
}

#[test]
fn test_sort_case_insensitive() {
let v = to_value(vec!["apple", "coconut", "Banana", "Dog"]).unwrap();
let mut args = HashMap::new();
args.insert("case_sensitive".to_string(), to_value(false).unwrap());
let result = sort(&v, &args);
assert!(result.is_ok());
assert_eq!(
result.unwrap(),
to_value(vec!["apple", "Banana", "coconut", "Dog"]).unwrap()
);
}

#[test]
fn test_sort_invalid_attribute() {
let v = to_value(vec![Foo { a: 3, b: 5 }]).unwrap();
Expand Down
34 changes: 31 additions & 3 deletions src/filter_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ pub struct SortPairs<K: Ord> {

type SortNumbers = SortPairs<OrderedF64>;
type SortBools = SortPairs<bool>;
type SortStrings = SortPairs<String>;
type SortArrays = SortPairs<ArrayLen>;

impl<K: GetValue> SortPairs<K> {
Expand Down Expand Up @@ -150,13 +149,42 @@ impl<K: GetValue> SortStrategy for SortPairs<K> {
}
}

pub fn get_sort_strategy_for_type(ty: &Value) -> Result<Box<dyn SortStrategy>> {
pub struct SortStrings {
pairs: Vec<(Value, String)>,
case_sensitive: bool,
}
impl SortStrings {
fn new(case_sensitive: bool) -> SortStrings {
SortStrings { pairs: Vec::new(), case_sensitive }
}
}
impl SortStrategy for SortStrings {
fn try_add_pair(&mut self, val: &Value, key: &Value) -> Result<()> {
let key_str = String::get_value(key)?;
self.pairs.push((val.clone(), key_str));
Ok(())
}
fn sort(&mut self) -> Vec<Value> {
if self.case_sensitive {
self.pairs.sort_by_key(|a| a.1.clone());
} else {
self.pairs.sort_by_key(|a| a.1.to_lowercase());
}

self.pairs.iter().map(|a| a.0.clone()).collect()
}
}

pub fn get_sort_strategy_for_type(
ty: &Value,
case_sensitive: bool,
) -> Result<Box<dyn SortStrategy>> {
use crate::Value::*;
match *ty {
Null => Err(Error::msg("Null is not a sortable value")),
Bool(_) => Ok(Box::<SortBools>::default()),
Number(_) => Ok(Box::<SortNumbers>::default()),
String(_) => Ok(Box::<SortStrings>::default()),
String(_) => Ok(Box::new(SortStrings::new(case_sensitive))),
Array(_) => Ok(Box::<SortArrays>::default()),
Object(_) => Err(Error::msg("Object is not a sortable value")),
}
Expand Down
Loading