Skip to content

Commit

Permalink
added wordcount filter (#649)
Browse files Browse the repository at this point in the history
  • Loading branch information
jqnatividad authored Nov 28, 2024
1 parent c21dde9 commit 11f89a2
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 1 deletion.
24 changes: 24 additions & 0 deletions minijinja-contrib/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,27 @@ pub fn truncate(state: &State, value: Value, kwargs: Kwargs) -> Result<String, E
result.push_str(end);
Ok(result)
}

/// Counts the words in a string.
///
/// ```jinja
/// {{ "Hello world!"|wordcount }}
/// ```
pub fn wordcount(value: Value) -> Result<Value, Error> {
let s = value.as_str().unwrap_or_default();
let mut count: u32 = 0;
let mut in_word = false;

// Iterate through characters, counting transitions from non-word to word chars
for c in s.chars() {
let is_word_char = c.is_alphanumeric() || c == '_';
if is_word_char && !in_word {
count += 1;
in_word = true;
} else if !is_word_char {
in_word = false;
}
}

Ok(Value::from(count))
}
67 changes: 66 additions & 1 deletion minijinja-contrib/tests/filters.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use minijinja::{context, Environment};
use minijinja_contrib::filters::pluralize;
use minijinja_contrib::filters::{pluralize, wordcount};
use similar_asserts::assert_eq;

#[test]
Expand Down Expand Up @@ -202,3 +202,68 @@ fn test_truncate() {
"invalid operation: expected length >= 3, got 1 (in <string>:1)"
);
}

#[test]
fn test_wordcount() {
let mut env = Environment::new();
env.add_filter("wordcount", wordcount);

assert_eq!(
env.render_str(
"{{ text|wordcount }}",
context! {
text => "Hello world! How are you?"
}
)
.unwrap(),
"5"
);

// Test empty string
assert_eq!(
env.render_str(
"{{ text|wordcount }}",
context! {
text => ""
}
)
.unwrap(),
"0"
);

// Test multiple whitespace
assert_eq!(
env.render_str(
"{{ text|wordcount }}",
context! {
text => "Hello world! Test"
}
)
.unwrap(),
"3"
);

// Test other word separators
assert_eq!(
env.render_str(
"{{ text|wordcount }}",
context! {
text => "hello-again@world! It's_me!"
}
)
.unwrap(),
"5"
);

// Test multiple other word separators
assert_eq!(
env.render_str(
"{{ text|wordcount }}",
context! {
text => "hello--again@-!world"
}
)
.unwrap(),
"3"
);
}

0 comments on commit 11f89a2

Please sign in to comment.