liberocks/lowdash is a Lodash inspired utility library to manipulate array and object
cargo add lowdash
This library has no dependencies outside the Rust standard library.
You can find the generated documentation here
Utility functions for array:
- associate
- chunk
- compact
- count
- count_by
- count_values
- count_values_by
- drop
- drop_right
- drop_right_while
- drop_while
- earliest
- earliest_by
- fill
- filter
- filter_map
- filter_reject
- find
- find_duplicates
- find_duplicates_by
- find_index_of
- find_key
- find_key_by
- find_last_index_of
- find_or_else
- find_uniques
- find_uniques_by
- first
- first_or
- first_or_empty
- flat_map
- flatten
- foreach
- foreach_while
- group_by
- index_of
- interleave
- is_sorted
- is_sorted_by_key
- key_by
- last
- last_index_of
- last_or
- last_or_empty
- latest
- latest_by
- map
- max
- max_by
- min
- min_by
- nth
- partition_by
- reduce
- reduce_right
- reject
- reject_map
- repeat
- repeat_by
- replace
- replace_all
- reverse
- sample
- samples
- shuffle
- slice
- slice_to_map
- splice
- subset
- times
- uniq
- uniq_by
- drop_by_index
Utility functions for string manipulation:
- camel_case
- capitalize
- char_length
- chunk_string
- ellipsis
- kebab_case
- pascal_case
- random_string
- snake_case
- substring
- words
Utility functions for object manipulation:
- assign
- entries
- from_entries
- from_pairs
- has_key
- invert
- keys
- map_entries
- map_keys
- map_to_slice
- map_values
- omit_by
- omit_by_keys
- omit_by_values
- pick_by
- pick_by_keys
- pick_by_values
- to_pairs
- uniq_keys
- uniq_values
- value_or
- values
Utility functions for math:
- nearest_power_of_two
- range
- range_from
- range_with_step
- clamp
- sum
- sum_by
- product
- product_by
- mean
- mean_by
- percentile
- median
- interpolate
- permutation
- combination
- duration_between
Converts a string to camelCase.
use lowdash::camel_case;
assert_eq!(camel_case("hello world"), "helloWorld");
assert_eq!(camel_case("foo-bar"), "fooBar");
assert_eq!(camel_case("lorem_ipsum"), "loremIpsum");
assert_eq!(camel_case("FooBarBazHello"), "fooBarBazHello");
Capitalizes the first letter of the input string and converts the rest to lowercase.
use lowdash::capitalize;
assert_eq!(capitalize("hello"), "Hello");
assert_eq!(capitalize("WORLD"), "World");
assert_eq!(capitalize("rUsT"), "Rust");
Returns the length of a string in Unicode characters.
use lowdash::char_length;
assert_eq!(char_length("hello"), 5);
assert_eq!(char_length("🌍world"), 6);
assert_eq!(char_length("こんにちは"), 5);
Splits a string into chunks of specified size.
use lowdash::chunk_string;
let result = chunk_string("hello", 2);
assert_eq!(result, vec!["he", "ll", "o"]);
Find the earliest item in a collection based on a custom iteratee function.
use std::time::{SystemTime, Duration};
use lowdash::earliest_by;
let t1 = SystemTime::UNIX_EPOCH;
let t2 = t1 + Duration::new(60, 0);
let t3 = t1 + Duration::new(120, 0);
let times = vec![t2, t1, t3];
let earliest_time = earliest_by(×, |&t| t);
assert_eq!(earliest_time, Some(t1));
#[derive(Debug, PartialEq, Clone)]
struct Event {
name: String,
timestamp: SystemTime,
}
let events = vec![
Event {
name: "Event1".to_string(),
timestamp: t2,
},
Event {
name: "Event2".to_string(),
timestamp: t1,
},
Event {
name: "Event3".to_string(),
timestamp: t3,
},
];
let earliest_event = earliest_by(&events, |e| e.timestamp);
assert_eq!(
earliest_event,
Some(Event {
name: "Event2".to_string(),
timestamp: t1,
})
);
Find the earliest time in a collection.
use std::time::{SystemTime, Duration};
use lowdash::earliest;
let t1 = SystemTime::UNIX_EPOCH;
let t2 = t1 + Duration::new(60, 0);
let t3 = t1 + Duration::new(120, 0);
let times = vec![t2, t1, t3];
let earliest_time = earliest(×);
assert_eq!(earliest_time, Some(t1));
Truncates a string and appends an ellipsis ("..."
) if it exceeds the specified length.
use lowdash::ellipsis;
let result = ellipsis("Hello, World!", 10);
assert_eq!(result, "Hello, ...");
let result = ellipsis("Short", 10);
assert_eq!(result, "Short");
let result = ellipsis("ExactLength", 11);
assert_eq!(result, "ExactLength");
let result = ellipsis(" Trimmed ", 6);
assert_eq!(result, "Tri...");
let result = ellipsis("Hi", 2);
assert_eq!(result, "Hi");
Find all duplicate elements in a collection based on a key generated by the iteratee function.
use lowdash::find_duplicates_by;
let numbers = vec![1, 2, 3, 4];
let result = find_duplicates_by(&numbers, |x| x % 2);
assert_eq!(result, vec![3, 4]); // Second occurrences of duplicated keys
use lowdash::find_duplicates_by;
#[derive(Debug, Clone, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 25 },
];
let result = find_duplicates_by(&people, |p| p.age);
assert_eq!(result, vec![
Person { name: "Carol".to_string(), age: 25 },
]);
Find all duplicate elements in a collection (elements that appear more than once).
use lowdash::find_duplicates;
let numbers = vec![1, 2, 2, 3, 3, 4];
let result = find_duplicates(&numbers);
assert_eq!(result, vec![2, 3]);
use lowdash::find_duplicates;
let words = vec!["apple", "banana", "apple", "cherry", "banana"];
let result = find_duplicates(&words);
assert_eq!(result, vec!["apple", "banana"]);
use lowdash::find_duplicates;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
];
let result = find_duplicates(&people);
assert_eq!(result, vec![Person { name: "Alice".to_string(), age: 25 }]);
Find the first item in a collection that satisfies a predicate and return its index.
use lowdash::find_index_of;
let numbers = vec![1, 2, 3, 4, 5];
let predicate = |x: &i32| *x == 3;
let result = find_index_of(&numbers, predicate);
assert_eq!(result, Some((&3, 2)));
use lowdash::find_index_of;
let numbers = vec![10, 20, 30, 40];
let result = find_index_of(&numbers, |x| *x > 25);
assert_eq!(result, Some((&30, 2)));
use lowdash::find_index_of;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = find_index_of(&people, |p| p.age > 30);
assert_eq!(result, Some((&Person { name: "Carol".to_string(), age: 35 }, 2)));
Find the key in a map that satisfies a predicate based on both key and value.
use lowdash::find_key_by;
let mut map = std::collections::HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = find_key_by(&map, |k, v| *k == "b" && *v == 2);
assert_eq!(result, Some(&"b"));
use lowdash::find_key_by;
let mut map = std::collections::HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = find_key_by(&map, |_, v| *v > 2);
assert_eq!(result, Some(&"c"));
Find the key in a map that corresponds to a given value.
use lowdash::find_key;
let mut map = std::collections::HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = find_key(&map, 2);
assert_eq!(result, Some(&"b"));
use lowdash::find_key;
let mut map = std::collections::HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = find_key(&map, 4);
assert_eq!(result, None);
use lowdash::find_key;
#[derive(Debug, PartialEq, Eq, Hash)]
struct Person {
name: String,
age: u32,
}
let mut map = std::collections::HashMap::new();
map.insert(Person { name: "Alice".to_string(), age: 25 }, "Engineer");
map.insert(Person { name: "Bob".to_string(), age: 30 }, "Manager");
map.insert(Person { name: "Carol".to_string(), age: 35 }, "Director");
let result = find_key(&map, "Manager");
assert_eq!(result, Some(&Person { name: "Bob".to_string(), age: 30 }));
Find the last item in a collection that satisfies a predicate and return its index.
use lowdash::find_last_index_of;
let numbers = vec![1, 2, 3, 4, 5, 3];
let predicate = |x: &i32| *x == 3;
let result = find_last_index_of(&numbers, predicate);
assert_eq!(result, Some((&3, 5)));
use lowdash::find_last_index_of;
let numbers = vec![10, 20, 30, 40, 30];
let result = find_last_index_of(&numbers, |x| *x > 25);
assert_eq!(result, Some((&30, 4)));
use lowdash::find_last_index_of;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 35 },
];
let result = find_last_index_of(&people, |p| p.age > 30);
assert_eq!(result, Some((&Person { name: "Dave".to_string(), age: 35 }, 3)));
Find the first item in a collection that satisfies a predicate.
use lowdash::find_or_else;
let numbers = vec![1, 2, 3, 4, 5];
let predicate = |x: &i32| *x == 3;
let result = find_or_else(&numbers, &0, predicate);
assert_eq!(result, &3);
use lowdash::find_or_else;
let numbers = vec![10, 20, 30, 40];
let result = find_or_else(&numbers, &0, |x| *x > 50);
assert_eq!(result, &0);
use lowdash::find_or_else;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let fallback = Person { name: "Unknown".to_string(), age: 0 };
let result = find_or_else(&people, &fallback, |p| p.age > 30);
assert_eq!(result, &Person { name: "Carol".to_string(), age: 35 });
Find all unique elements in a collection (elements that appear exactly once).
use lowdash::find_uniques;
let numbers = vec![1, 2, 2, 3, 3, 4];
let result = find_uniques(&numbers);
assert_eq!(result, vec![1, 4]);
use lowdash::find_uniques;
let words = vec!["apple", "banana", "apple", "cherry"];
let result = find_uniques(&words);
assert_eq!(result, vec!["banana", "cherry"]);
use lowdash::find_uniques;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
];
let result = find_uniques(&people);
assert_eq!(result, vec![Person { name: "Bob".to_string(), age: 30 }]);
Find all unique elements in a collection based on a key generated by the iteratee function.
use lowdash::find_uniques_by;
let numbers = vec![1, 2, 3, 4];
let result = find_uniques_by(&numbers, |x| x % 2); // Group by even/odd
assert_eq!(result, vec![]); // No unique remainders
use lowdash::find_uniques_by;
#[derive(Debug, Clone, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 25 },
];
let result = find_uniques_by(&people, |p| p.age);
assert_eq!(result, vec![Person { name: "Bob".to_string(), age: 30 }]);
Find the first item in a collection that satisfies a predicate.
use lowdash::find;
let numbers = vec![1, 2, 3, 4, 5];
let predicate = |x: &i32| *x == 3;
let result = find(&numbers, predicate);
assert_eq!(result, Some(&3));
use lowdash::find;
let numbers = vec![10, 20, 30, 40];
let result = find(&numbers, |x| *x > 25);
assert_eq!(result, Some(&30));
use lowdash::find;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = find(&people, |p| p.age > 30);
assert_eq!(result, Some(&Person { name: "Carol".to_string(), age: 35 }));
Returns the first item from the collection.
use lowdash::first_or_empty;
let numbers = vec![1, 2, 3];
let first_num = first_or_empty(&numbers);
assert_eq!(first_num, 1);
let empty: Vec<i32> = vec![];
let first_num = first_or_empty(&empty);
assert_eq!(first_num, 0); // i32::default() is 0
use lowdash::first_or_empty;
#[derive(Debug, PartialEq, Clone, Default)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
];
let first_person = first_or_empty(&people);
assert_eq!(first_person, Person { name: "Alice".to_string(), age: 25 });
let empty_people: Vec<Person> = vec![];
let first_person = first_or_empty(&empty_people);
assert_eq!(first_person, Person::default());
Returns the first item from the collection.
use lowdash::first_or;
let numbers = vec![1, 2, 3];
let first_num = first_or(&numbers, 10);
assert_eq!(first_num, 1);
let empty: Vec<i32> = vec![];
let first_num = first_or(&empty, 10);
assert_eq!(first_num, 10);
use lowdash::first_or;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
];
let first_person = first_or(&people, Person { name: "Default".to_string(), age: 0 });
assert_eq!(first_person, Person { name: "Alice".to_string(), age: 25 });
let empty_people: Vec<Person> = vec![];
let first_person = first_or(&empty_people, Person { name: "Default".to_string(), age: 0 });
assert_eq!(first_person, Person { name: "Default".to_string(), age: 0 });
Returns the first item from the collection.
use lowdash::first;
let numbers = vec![1, 2, 3];
let (first_num, exists) = first(&numbers);
assert_eq!(first_num, 1);
assert!(exists);
let empty: Vec<i32> = vec![];
let (first_num, exists) = first(&empty);
assert_eq!(first_num, 0); // i32::default() is 0
assert!(!exists);
Finds the position of the first occurrence of an element in a collection.
use lowdash::index_of;
let collection = vec![1, 2, 3, 4, 5];
let index = index_of(&collection, 3);
assert_eq!(index, 2);
use lowdash::index_of;
let collection = vec!["apple", "banana", "cherry"];
let index = index_of(&collection, "banana");
assert_eq!(index, 1);
use lowdash::index_of;
let collection = vec![1, 2, 3, 4, 5];
let index = index_of(&collection, 6);
assert_eq!(index, -1);
Converts a string to kebab-case.
use lowdash::kebab_case;
assert_eq!(kebab_case("hello world"), "hello-world");
assert_eq!(kebab_case("foo-bar"), "foo-bar");
assert_eq!(kebab_case("lorem_ipsum"), "lorem-ipsum");
assert_eq!(kebab_case("FooBarBazHello"), "foo-bar-baz-hello");
assert_eq!(kebab_case("helloWorld"), "hello-world");
Finds the position of the last occurrence of an element in a collection.
use lowdash::last_index_of;
let collection = vec![1, 2, 3, 2, 1];
let index = last_index_of(&collection, 2);
assert_eq!(index, 3);
use lowdash::last_index_of;
let collection = vec!["apple", "banana", "cherry", "banana"];
let index = last_index_of(&collection, "banana");
assert_eq!(index, 3);
use lowdash::last_index_of;
let collection = vec![1, 2, 3, 4, 5];
let index = last_index_of(&collection, 6);
assert_eq!(index, -1);
Returns the last item from the collection.
use lowdash::last_or_empty;
let numbers = vec![1, 2, 3];
let last_num = last_or_empty(&numbers);
assert_eq!(last_num, 3);
let empty: Vec<i32> = vec![];
let last_num = last_or_empty(&empty);
assert_eq!(last_num, 0); // i32::default() is 0
use lowdash::last_or_empty;
#[derive(Debug, PartialEq, Clone, Default)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
];
let last_person = last_or_empty(&people);
assert_eq!(last_person, Person { name: "Bob".to_string(), age: 30 });
let empty_people: Vec<Person> = vec![];
let last_person = last_or_empty(&empty_people);
assert_eq!(last_person, Person::default());
Returns the last item from the collection.
use lowdash::last_or;
let numbers = vec![1, 2, 3];
let last_num = last_or(&numbers, 10);
assert_eq!(last_num, 3);
let empty: Vec<i32> = vec![];
let last_num = last_or(&empty, 10);
assert_eq!(last_num, 10);
Returns the last item from the collection.
use lowdash::last;
let numbers = vec![1, 2, 3];
let (last_num, exists) = last(&numbers);
assert_eq!(last_num, 3);
assert!(exists);
let empty: Vec<i32> = vec![];
let (last_num, exists) = last(&empty);
assert_eq!(last_num, 0); // i32::default() is 0
assert!(!exists);
use lowdash::last;
#[derive(Debug, PartialEq, Clone, Default)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
];
let (last_person, exists) = last(&people);
assert_eq!(last_person, Person { name: "Bob".to_string(), age: 30 });
assert!(exists);
let empty_people: Vec<Person> = vec![];
let (last_person, exists) = last(&empty_people);
assert_eq!(last_person, Person::default());
assert!(!exists);
Returns the item from the collection for which the iteratee returns the latest SystemTime
.
use std::time::{SystemTime, Duration};
use lowdash::latest_by;
#[derive(Debug, PartialEq, Clone)]
struct Record {
id: u32,
timestamp: SystemTime,
}
impl Default for Record {
fn default() -> Self {
Record {
id: 0,
timestamp: SystemTime::UNIX_EPOCH,
}
}
}
let records = vec![
Record {
id: 1,
timestamp: SystemTime::UNIX_EPOCH + Duration::new(100, 0),
},
Record {
id: 2,
timestamp: SystemTime::UNIX_EPOCH + Duration::new(200, 0),
},
Record {
id: 3,
timestamp: SystemTime::UNIX_EPOCH + Duration::new(150, 0),
},
];
let latest_record = latest_by(&records, |r| r.timestamp);
assert_eq!(latest_record.id, 2);
Returns the latest SystemTime
from the provided arguments.
use std::time::{SystemTime, Duration};
use lowdash::latest;
let now = SystemTime::now();
let later = now + Duration::new(10, 0);
let latest_time = latest(&[now, later]);
assert_eq!(latest_time, later);
Find the maximum element in a collection based on a custom comparison function.
use lowdash::max_by;
#[derive(Debug, PartialEq, Eq, Clone)]
struct Person {
age: u32,
name: String,
}
let people = vec![
Person { age: 25, name: "Alice".to_string() },
Person { age: 30, name: "Bob".to_string() },
Person { age: 20, name: "Carol".to_string() },
];
let result = max_by(&people, |a, b| a.age > b.age);
assert_eq!(
result,
Some(Person { age: 30, name: "Bob".to_string() })
);
Find the maximum element in a collection.
use lowdash::max;
let numbers = vec![5, 3, 8, 1, 4];
let result = max(&numbers);
assert_eq!(result, Some(8));
use lowdash::max;
let strings = vec!["apple", "banana", "cherry"];
let result = max(&strings);
assert_eq!(result, Some("cherry"));
use lowdash::max;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Cia".to_string(), age: 20 },
];
let result = max(&people);
assert_eq!(
result,
Some(Person { name: "Cia".to_string(), age: 20 })
);
use lowdash::max;
let collection = vec![3.14, 2.71, -1.0, 0.0];
let result = max(&collection);
assert_eq!(result, Some(3.14));
Find the minimum element in a collection based on a custom comparison function.
use lowdash::min_by;
let numbers = vec![5, 3, 8, 1, 4];
let min = min_by(&numbers, |a, b| a < b);
assert_eq!(min, Some(1));
let strings = vec!["apple", "banana", "cherry"];
let min = min_by(&strings, |a, b| a.len() < b.len());
assert_eq!(min, Some("apple"));
let empty: Vec<i32> = vec![];
let min = min_by(&empty, |a, b| a < b);
assert_eq!(min, None);
Find the minimum element in a collection.
use lowdash::min;
let numbers = vec![5, 3, 8, 1, 4];
let result = min(&numbers);
assert_eq!(result, Some(1));
use lowdash::min;
let strings = vec!["apple", "banana", "cherry"];
let result = min(&strings);
assert_eq!(result, Some("apple"));
use lowdash::min;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 20 },
];
let result = min(&people);
assert_eq!(
result,
Some(Person { name: "Alice".to_string(), age: 25 })
);
use lowdash::min;
let collection = vec![3.14, 2.71, -1.0, 0.0];
let result = min(&collection);
assert_eq!(result, Some(-1.0));
Calculates the smallest power of two greater than or equal to the given capacity.
use lowdash::nearest_power_of_two;
assert_eq!(nearest_power_of_two(0), 1);
assert_eq!(nearest_power_of_two(1), 1);
assert_eq!(nearest_power_of_two(5), 8);
assert_eq!(nearest_power_of_two(16), 16);
assert_eq!(nearest_power_of_two(17), 32);
Returns the nth element from the collection.
use lowdash::nth;
let numbers = vec![1, 2, 3, 4, 5];
let result = nth(&numbers, 2);
assert_eq!(result.unwrap(), &3);
let result = nth(&numbers, -2);
assert_eq!(result.unwrap(), &4);
let result = nth(&numbers, 10);
assert!(result.is_err());
Converts a string to PascalCase.
use lowdash::pascal_case;
assert_eq!(pascal_case("hello world"), "HelloWorld");
assert_eq!(pascal_case("foo-bar"), "FooBar");
assert_eq!(pascal_case("lorem_ipsum"), "LoremIpsum");
Generates a random string of a specified size using the provided charset.
use lowdash::common::ALPHANUMERIC_CHARSET;
use lowdash::random_string;
let charset = ALPHANUMERIC_CHARSET;
let random_str = random_string(10, charset);
assert_eq!(random_str.len(), 10);
for c in random_str.chars() {
assert!(charset.contains(&c));
}
Returns a pseudo-random element from the collection.
use lowdash::sample;
let numbers = vec![1, 2, 3, 4, 5];
let result = sample(&numbers);
assert!(numbers.contains(&result));
let empty: Vec<i32> = vec![];
let result = sample(&empty);
assert_eq!(result, 0); // i32::default()
Returns a slice of pseudo-randomly selected elements from the collection.
use lowdash::samples;
let numbers = vec![1, 2, 3, 4, 5];
let result = samples(&numbers, 3);
assert_eq!(result.len(), 3);
assert!(result.iter().all(|x| numbers.contains(x)));
Converts a string to snake_case.
use lowdash::snake_case;
assert_eq!(snake_case("hello world"), "hello_world");
assert_eq!(snake_case("foo-bar"), "foo_bar");
assert_eq!(snake_case("lorem_ipsum"), "lorem_ipsum");
assert_eq!(snake_case("FooBarBazHello"), "foo_bar_baz_hello");
assert_eq!(snake_case("fooBarBazHello"), "foo_bar_baz_hello");
Extracts a substring from the given string based on the specified offset and length.
use lowdash::substring;
let s = String::from("Hello, World!");
assert_eq!(substring(&s, 7, 5), "World");
let s = String::from("Hello, World!");
assert_eq!(substring(&s, -6, 5), "World");
let s = String::from("Hello, World!");
assert_eq!(substring(&s, 100, 5), "");
let s = String::from("Hello\x00World!");
assert_eq!(substring(&s, 0, 10), "HelloWorld");
Splits a string into words based on casing, digits, and separators.
use lowdash::words;
let result = words("Int8Value");
assert_eq!(result, vec!["Int", "8", "Value"]);
let result = words("hello_world");
assert_eq!(result, vec!["hello", "world"]);
let result = words("fooBarBazHello");
assert_eq!(result, vec!["foo", "Bar", "Baz", "Hello"]);
Reject items from a collection that satisfy a predicate.
use lowdash::reject;
let numbers = vec![1, 2, 3, 4, 5];
let result = reject(&numbers, |x, _| *x % 2 == 0);
assert_eq!(result, vec![&1, &3, &5]);
Filter items from a collection that satisfy a predicate.
use lowdash::filter;
let numbers = vec![1, 2, 3, 4, 5];
let result = filter(&numbers, |x, _| *x % 2 == 0);
assert_eq!(result, vec![&2, &4]);
use lowdash::filter;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = filter(&people, |p, _| p.age > 30);
assert_eq!(result, vec![&people[2]]);
Apply a function to each item in a collection, producing a new collection of results.
use lowdash::map;
let numbers = vec![1, 2, 3, 4, 5];
let result = map(&numbers, |x, _| x * 2);
assert_eq!(result, vec![2, 4, 6, 8, 10]);
use lowdash::map;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let names: Vec<String> = map(&people, |p, _| p.name.clone());
assert_eq!(names, vec!["Alice", "Bob", "Carol"]);
Apply a function to each item in a collection, filtering and transforming items based on a callback.
use lowdash::filter_map;
let numbers = vec![1, 2, 3, 4, 5];
// Double even numbers
let result = filter_map(&numbers, |x, _| {
if *x % 2 == 0 {
(x * 2, true)
} else {
(0, false)
}
});
assert_eq!(result, vec![4, 8]);
use lowdash::filter_map;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
// Extract names of people older than 28
let names: Vec<String> = filter_map(&people, |p, _| {
if p.age > 28 {
(p.name.clone(), true)
} else {
(String::new(), false)
}
});
assert_eq!(names, vec!["Bob".to_string(), "Carol".to_string()]);
Apply a function to each item in a collection, flattening the results based on a callback.
use lowdash::flat_map;
let numbers = vec![1, 2, 3];
// For each number, generate a vector containing the number and its double
let result = flat_map(&numbers, |x, _| vec![*x, *x * 2]);
assert_eq!(result, vec![1, 2, 2, 4, 3, 6]);
use lowdash::flat_map;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
hobbies: Vec<String>,
}
let people = vec![
Person {
name: "Alice".to_string(),
hobbies: vec!["Reading".to_string(), "Cycling".to_string()],
},
Person {
name: "Bob".to_string(),
hobbies: vec!["Cooking".to_string()],
},
];
// Extract all hobbies from the list of people
let all_hobbies: Vec<String> = flat_map(&people, |person, _| person.hobbies.clone());
assert_eq!(
all_hobbies,
vec![
"Reading".to_string(),
"Cycling".to_string(),
"Cooking".to_string()
]
);
Apply a function to each item in a collection, accumulating a single result.
use lowdash::reduce;
let numbers = vec![1, 2, 3, 4, 5];
// Sum of all numbers
let sum = reduce(&numbers, |acc, x, _| acc + x, 0);
assert_eq!(sum, 15);
use lowdash::reduce;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
// Concatenate all names
let all_names = reduce(&people, |acc, person, _| format!("{} {}", acc, person.name), String::new());
assert_eq!(all_names.trim(), "Alice Bob Carol");
Apply a function to each item in a collection, accumulating a single result from right to left.
use lowdash::reduce_right;
let numbers = vec![1, 2, 3, 4, 5];
// Sum of all numbers using reduce_right
let sum = reduce_right(&numbers, |acc, x, _| acc + x, 0);
assert_eq!(sum, 15);
use lowdash::reduce_right;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
// Concatenate all names in reverse order
let all_names = reduce_right(&people, |acc, person, _| {
if acc.is_empty() {
person.name.clone()
} else {
format!("{} {}", acc, person.name)
}
}, String::new());
assert_eq!(all_names, "Carol Bob Alice");
Execute a function on each item in a collection.
use lowdash::foreach;
let numbers = vec![1, 2, 3, 4, 5];
let mut sum = 0;
foreach(&numbers, |x, _| sum += x);
assert_eq!(sum, 15);
use lowdash::foreach;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let mut names = Vec::new();
foreach(&people, |p, _| names.push(p.name.clone()));
assert_eq!(names, vec!["Alice", "Bob", "Carol"]);
Execute a function on each item in a collection until the iteratee returns false
.
use lowdash::foreach_while;
let numbers = vec![1, 2, 3, 4, 5];
let mut sum = 0;
foreach_while(&numbers, |x, _| {
sum += x;
true
});
assert_eq!(sum, 15);
use lowdash::foreach_while;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let mut names = Vec::new();
foreach_while(&people, |p, _| {
names.push(p.name.clone());
true
});
assert_eq!(names, vec!["Alice", "Bob", "Carol"]);
use lowdash::foreach_while;
let numbers = vec![10, 20, 30, 40, 50];
let mut collected = Vec::new();
foreach_while(&numbers, |x, index| {
if *x < 35 {
collected.push((*x, index));
true
} else {
false
}
});
assert_eq!(collected, vec![(10, 0), (20, 1), (30, 2)]);
Generates a collection by invoking the provided function iteratee
a specified number of times.
use lowdash::times;
let result = times(5, |i| i * 2);
assert_eq!(result, vec![0, 2, 4, 6, 8]);
use lowdash::times;
let result = times(3, |i| format!("Item {}", i));
assert_eq!(result, vec!["Item 0", "Item 1", "Item 2"]);
Remove duplicate elements from a collection, preserving the order of their first occurrence.
use lowdash::uniq;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let unique_numbers = uniq(&numbers);
assert_eq!(unique_numbers, vec![1, 2, 3, 4, 5]);
use lowdash::uniq;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let unique_people = uniq(&people);
assert_eq!(unique_people, vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
]);
Remove duplicate elements from a collection based on a key extracted by a provided function, preserving the order of their first occurrence.
use lowdash::uniq_by;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let unique_numbers = uniq_by(&numbers, |x| *x);
assert_eq!(unique_numbers, vec![1, 2, 3, 4, 5]);
use lowdash::uniq_by;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let unique_people = uniq_by(&people, |p| p.name.clone());
assert_eq!(unique_people, vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
]);
Group elements of a collection based on a key extracted by a provided function, preserving the order of their first occurrence.
use lowdash::group_by;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let grouped = group_by(&numbers, |x| *x % 2 == 0);
assert_eq!(grouped.get(&false), Some(&vec![1, 3, 3, 5]));
assert_eq!(grouped.get(&true), Some(&vec![2, 2, 4]));
use lowdash::group_by;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 25 },
];
let grouped = group_by(&people, |p| p.age);
assert_eq!(grouped.get(&25), Some(&vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 25 },
]));
assert_eq!(grouped.get(&30), Some(&vec![
Person { name: "Bob".to_string(), age: 30 },
]));
Divide a collection into smaller chunks of a specified size, preserving the order of elements.
use lowdash::chunk;
let numbers = vec![1, 2, 3, 4, 5, 6, 7];
let chunks = chunk(&numbers, 3);
assert_eq!(
chunks,
vec![vec![1, 2, 3], vec![4, 5, 6], vec![7]]
);
use lowdash::chunk;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
];
let chunks = chunk(&people, 2);
assert_eq!(
chunks,
vec![
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
],
vec![
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
],
]
);
Divide a collection into partitions based on a key extracted by a provided function, preserving the order of elements and the order of partitions as they first appear.
use lowdash::partition_by;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let partitions = partition_by(&numbers, |x| *x);
assert_eq!(
partitions,
vec![vec![1], vec![2, 2], vec![3, 3], vec![4], vec![5]]
);
use lowdash::partition_by;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let partitions = partition_by(&people, |p| p.age);
assert_eq!(
partitions,
vec![
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Alice".to_string(), age: 25 },
],
vec![
Person { name: "Bob".to_string(), age: 30 },
],
vec![
Person { name: "Carol".to_string(), age: 35 },
],
]
);
Flatten a collection of slices into a single vector, preserving the order of elements.
use lowdash::flatten;
let nested = vec![vec![1, 2], vec![3, 4], vec![5]];
let flat = flatten(&nested);
assert_eq!(flat, vec![1, 2, 3, 4, 5]);
use lowdash::flatten;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people_groups = vec![
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
],
vec![
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
],
];
let flat_people = flatten(&people_groups);
assert_eq!(
flat_people,
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
]
);
Interleave multiple collections into a single vector, preserving the order of elements.
use lowdash::interleave;
let a = vec![1, 2, 3];
let b = vec![4, 5, 6, 7];
let c = vec![8, 9];
let result = interleave(&[&a[..], &b[..], &c[..]]);
assert_eq!(result, vec![1, 4, 8, 2, 5, 9, 3, 6, 7]);
use lowdash::interleave;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let group1 = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
];
let group2 = vec![
Person { name: "Carol".to_string(), age: 35 },
];
let group3 = vec![
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Eve".to_string(), age: 45 },
Person { name: "Frank".to_string(), age: 50 },
];
let interleaved = interleave(&[&group1[..], &group2[..], &group3[..]]);
assert_eq!(
interleaved,
vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Eve".to_string(), age: 45 },
Person { name: "Frank".to_string(), age: 50 },
]
);
Shuffle a collection, returning a new vector with the elements in random order.
use lowdash::shuffle;
let numbers = vec![1, 2, 3, 4, 5];
let shuffled = shuffle(&numbers);
assert_eq!(shuffled.len(), numbers.len());
assert!(shuffled.contains(&1));
assert!(shuffled.contains(&2));
assert!(shuffled.contains(&3));
assert!(shuffled.contains(&4));
assert!(shuffled.contains(&5));
Reverse a collection, returning a new vector with the elements in reverse order.
use lowdash::reverse;
let numbers = vec![1, 2, 3, 4, 5];
let reversed = reverse(&numbers);
assert_eq!(reversed, vec![5, 4, 3, 2, 1]);
use lowdash::reverse;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let reversed_people = reverse(&people);
assert_eq!(reversed_people, vec![
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
]);
Fill a collection with a specified value, returning a new vector with all elements set to the initial value.
use lowdash::fill;
let numbers = vec![1, 2, 3, 4, 5];
let filled = fill(&numbers, 0);
assert_eq!(filled, vec![0, 0, 0, 0, 0]);
use lowdash::fill;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let filled_people = fill(&people, Person { name: "Dave".to_string(), age: 40 });
assert_eq!(
filled_people,
vec![
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Dave".to_string(), age: 40 },
]
);
Fill a collection with a specified value, returning a new vector with all elements set to the initial value.
use lowdash::repeat;
let filled = repeat(5, 0);
assert_eq!(filled, vec![0, 0, 0, 0, 0]);
use lowdash::repeat;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let filled_people = repeat(3, Person { name: "Dave".to_string(), age: 40 });
assert_eq!(
filled_people,
vec![
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Dave".to_string(), age: 40 },
Person { name: "Dave".to_string(), age: 40 },
]
);
Repeat a specified value count
times by applying a predicate function to each index, returning a new vector with the generated elements.
use lowdash::repeat_by;
let filled = repeat_by(5, |i| i * 2);
assert_eq!(filled, vec![0, 2, 4, 6, 8]);
use lowdash::repeat_by;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let filled_people = repeat_by(3, |i| Person {
name: format!("Person {}", i + 1),
age: 20 + i as u32 * 5,
});
assert_eq!(
filled_people,
vec![
Person { name: "Person 1".to_string(), age: 20 },
Person { name: "Person 2".to_string(), age: 25 },
Person { name: "Person 3".to_string(), age: 30 },
]
);
Creates a HashMap
by mapping each element in a collection to a key using an iteratee function.
use lowdash::key_by;
use std::collections::HashMap;
let numbers = vec![1, 2, 3, 4, 5];
let map = key_by(&numbers, |&x| x % 2);
let mut expected = HashMap::new();
expected.insert(1, 5); // Last odd number
expected.insert(0, 4); // Last even number
assert_eq!(map, expected);
use lowdash::key_by;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Charlie".to_string(), age: 35 },
];
let map = key_by(&people, |person| person.name.clone());
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), people[0].clone());
expected.insert("Bob".to_string(), people[1].clone());
expected.insert("Charlie".to_string(), people[2].clone());
assert_eq!(map, expected);
use lowdash::key_by;
use std::collections::HashMap;
let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = key_by(&strings, |s| s.chars().next().unwrap());
let mut expected = HashMap::new();
expected.insert('a', "apricot");
expected.insert('b', "blueberry");
assert_eq!(map, expected);
Creates a HashMap
by transforming each element in a collection into a key-value pair using a provided function.
use lowdash::associate;
use std::collections::HashMap;
let numbers = vec![1, 2, 3, 4, 5];
let map = associate(&numbers, |&x| (x, x * x));
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 4);
expected.insert(3, 9);
expected.insert(4, 16);
expected.insert(5, 25);
assert_eq!(map, expected);
use lowdash::associate;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Charlie".to_string(), age: 35 },
];
let map = associate(&people, |person| (person.name.clone(), person.age));
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), 25);
expected.insert("Bob".to_string(), 30);
expected.insert("Charlie".to_string(), 35);
assert_eq!(map, expected);
use lowdash::associate;
use std::collections::HashMap;
let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = associate(&strings, |s| (s.chars().next().unwrap(), s.len()));
let mut expected = HashMap::new();
expected.insert('a', 7); // "apricot" has 7 characters
expected.insert('b', 9); // "blueberry" has 9 characters
assert_eq!(map, expected);
Transforms a slice of items into a HashMap
by applying a provided function to each item.
use lowdash::slice_to_map;
use std::collections::HashMap;
let numbers = vec![1, 2, 3, 4, 5];
let map = slice_to_map(&numbers, |&x| (x, x * x));
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 4);
expected.insert(3, 9);
expected.insert(4, 16);
expected.insert(5, 25);
assert_eq!(map, expected);
use lowdash::slice_to_map;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Charlie".to_string(), age: 35 },
];
let map = slice_to_map(&people, |person| (person.name.clone(), person.age));
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), 25);
expected.insert("Bob".to_string(), 30);
expected.insert("Charlie".to_string(), 35);
assert_eq!(map, expected);
use lowdash::slice_to_map;
use std::collections::HashMap;
let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = slice_to_map(&strings, |s| (s.chars().next().unwrap(), s.len()));
let mut expected = HashMap::new();
expected.insert('a', 7); // "apricot" has 7 characters
expected.insert('b', 9); // "blueberry" has 9 characters
assert_eq!(map, expected);
Removes the first n
elements from a collection and returns the remaining elements.
use lowdash::drop;
let numbers = vec![1, 2, 3, 4, 5];
let result = drop(&numbers, 2);
assert_eq!(result, vec![3, 4, 5]);
use lowdash::drop;
let letters = vec!['a', 'b', 'c', 'd'];
let result = drop(&letters, 10);
assert_eq!(result, vec![]);
Removes the last n
elements from a collection and returns the remaining elements.
use lowdash::drop_right;
let numbers = vec![1, 2, 3, 4, 5];
let result = drop_right(&numbers, 2);
assert_eq!(result, vec![1, 2, 3]);
use lowdash::drop_right;
let letters = vec!['a', 'b', 'c', 'd'];
let result = drop_right(&letters, 10);
assert_eq!(result, vec![]);
Removes elements from the beginning of a collection as long as a predicate returns true
, and returns the remaining elements. As soon as the predicate returns false
, the function stops dropping elements.
use lowdash::drop_while;
let numbers = vec![1, 2, 3, 4, 5];
let result = drop_while(&numbers, |&x| x < 3);
assert_eq!(result, vec![3, 4, 5]);
use lowdash::drop_while;
let letters = vec!['a', 'b', 'c', 'd'];
let result = drop_while(&letters, |&c| c < 'c');
assert_eq!(result, vec!['c', 'd']);
Removes elements from the end of a collection as long as a predicate returns true
, and returns the remaining elements. As soon as the predicate returns false
, the function stops dropping elements.
use lowdash::drop_right_while;
let numbers = vec![1, 2, 3, 4, 5];
let result = drop_right_while(&numbers, |&x| x > 3);
assert_eq!(result, vec![1, 2, 3]);
use lowdash::drop_right_while;
let letters = vec!['a', 'b', 'c', 'd', 'e'];
let result = drop_right_while(&letters, |&c| c != 'c');
assert_eq!(result, vec!['a', 'b', 'c']);
Removes elements from a collection at the specified indices. Supports negative indices which count from the end of the collection. Indices that are out of bounds are ignored.
use lowdash::drop_by_index;
let numbers = vec![1, 2, 3, 4, 5];
let result = drop_by_index(&numbers, &[1, 3]);
assert_eq!(result, vec![1, 3, 5]);
use lowdash::drop_by_index;
let letters = vec!['a', 'b', 'c', 'd', 'e'];
let result = drop_by_index(&letters, &[0, -1]);
assert_eq!(result, vec!['b', 'c', 'd']);
Applies a callback function to each item in a collection along with its index and collects the results where the callback returns false
.
use lowdash::reject_map;
let numbers = vec![1, 2, 3, 4, 5];
// Collect squares of odd numbers
let result = reject_map(&numbers, |&x, _| (x * x, x % 2 == 0));
assert_eq!(result, vec![1, 9, 25]);
use lowdash::reject_map;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
// Collect names of people who are not above 30
let result = reject_map(&people, |person, _| (person.name.clone(), person.age > 30));
assert_eq!(result, vec!["Alice".to_string(), "Bob".to_string()]);
Filters a collection into two separate vectors based on a predicate function.
use lowdash::filter_reject;
let numbers = vec![1, 2, 3, 4, 5];
// Separate even and odd numbers
let (evens, odds) = filter_reject(&numbers, |&x, _| x % 2 == 0);
assert_eq!(evens, vec![2, 4]);
assert_eq!(odds, vec![1, 3, 5]);
use lowdash::filter_reject;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
// Separate people who are at least 30 years old
let (adults, juniors) = filter_reject(&people, |person, _| person.age >= 30);
assert_eq!(adults, vec![
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
]);
assert_eq!(juniors, vec![
Person { name: "Alice".to_string(), age: 25 },
]);
Counts the number of occurrences of a specific value in a collection.
use lowdash::count;
let numbers = vec![1, 2, 2, 3, 4, 2];
let result = count(&numbers, 2);
assert_eq!(result, 3);
use lowdash::count;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
];
let count_alice = count(&people, Person { name: "Alice".to_string(), age: 25 });
assert_eq!(count_alice, 2);
Counts the number of elements in a collection that satisfy a given predicate.
use lowdash::count_by;
let numbers = vec![1, 2, 3, 4, 5];
// Count even numbers
let result = count_by(&numbers, |&x| x % 2 == 0);
assert_eq!(result, 2);
use lowdash::count_by;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 30 },
];
// Count people who are at least 30 years old
let count_adults = count_by(&people, |p| p.age >= 30);
assert_eq!(count_adults, 3);
Counts the number of occurrences of each value in a collection.
use lowdash::count_values;
use std::collections::HashMap;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let result = count_values(&numbers);
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 2);
expected.insert(3, 2);
expected.insert(4, 1);
expected.insert(5, 1);
assert_eq!(result, expected);
use lowdash::count_values;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = count_values(&people);
let mut expected = HashMap::new();
expected.insert(
Person { name: "Alice".to_string(), age: 25 },
2
);
expected.insert(
Person { name: "Bob".to_string(), age: 30 },
1
);
expected.insert(
Person { name: "Carol".to_string(), age: 35 },
1
);
assert_eq!(result, expected);
Counts the number of occurrences of each value in a collection after applying a mapper function.
use lowdash::count_values_by;
use std::collections::HashMap;
let chars = vec!['a', 'b', 'a', 'c', 'b', 'd'];
let result = count_values_by(&chars, |x| x.clone());
let mut expected = HashMap::new();
expected.insert('a', 2);
expected.insert('b', 2);
expected.insert('c', 1);
expected.insert('d', 1);
assert_eq!(result, expected);
use lowdash::count_values_by;
use std::collections::HashMap;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let result = count_values_by(&numbers, |x| *x);
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 2);
expected.insert(3, 2);
expected.insert(4, 1);
expected.insert(5, 1);
assert_eq!(result, expected);
Returns a subset of the collection based on the provided offset and length.
use lowdash::subset;
let numbers = vec![1, 2, 3, 4, 5];
let result = subset(&numbers, 1, 3);
assert_eq!(result, vec![2, 3, 4]);
Returns a subset of the collection based on the provided start and end indices.
use lowdash::slice;
let numbers = vec![1, 2, 3, 4, 5];
let result = slice(&numbers, 1, 3);
assert_eq!(result, vec![2, 3]);
use lowdash::slice;
let numbers = vec![1, 2, 3, 4, 5];
let result = slice(&numbers, -3, -1);
assert_eq!(result, vec![3, 4]);
use lowdash::slice;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
Person { name: "Dave".to_string(), age: 40 },
];
let result = slice(&people, 1, 3);
assert_eq!(
result,
vec![
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
]
);
Replaces occurrences of a specified value in a collection with a new value, up to a maximum number of replacements.
use lowdash::replace;
let numbers = vec![1, 2, 2, 3, 4, 2, 5];
let result = replace(&numbers, 2, 9, 2);
assert_eq!(result, vec![1, 9, 9, 3, 4, 2, 5]);
use lowdash::replace;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let new_person = Person { name: "Dave".to_string(), age: 40 };
let result = replace(&people, people[0].clone(), new_person.clone(), 1);
assert_eq!(result, vec![new_person, people[1].clone(), people[2].clone(), people[3].clone()]);
Replaces all occurrences of a specified value in a collection with a new value.
use lowdash::replace_all;
let numbers = vec![1, 2, 2, 3, 4, 2, 5];
let result = replace_all(&numbers, 2, 9);
assert_eq!(result, vec![1, 9, 9, 3, 4, 9, 5]);
use lowdash::replace_all;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let dave = Person { name: "Dave".to_string(), age: 40 };
let result = replace_all(&people, people[0].clone(), dave.clone());
assert_eq!(
result,
vec![
dave.clone(),
people[1].clone(),
dave.clone(),
people[3].clone(),
]
);
Removes all zero-valued elements from a collection, preserving the order of non-zero elements.
This function iterates over a slice of items, removing each element that is equal to the zero value.
The zero value is determined by the Default
trait implementation for the type T
.
The function preserves the order of the remaining elements and does not modify the original collection.
Time Complexity: O(n), where n is the number of elements in the collection.
collection
- A slice of items from which to remove zero-valued elements.
T
- The type of elements in the collection. Must implementPartialEq
,Clone
, andDefault
.
Vec<T>
- A new vector containing only the non-zero elements from the input collection.
use lowdash::compact;
let numbers = vec![0, 1, 0, 2, 3, 0, 4];
let compacted = compact(&numbers);
assert_eq!(compacted, vec![1, 2, 3, 4]);
use lowdash::compact;
#[derive(Debug, PartialEq, Clone, Default)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "".to_string(), age: 0 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "".to_string(), age: 0 },
Person { name: "Dave".to_string(), age: 40 },
];
let compacted = compact(&people);
assert_eq!(
compacted,
vec![
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Dave".to_string(), age: 40 },
]
);
use lowdash::compact;
let floats = vec![0.0, 1.1, 0.0, 2.2, 3.3, 0.0, 4.4];
let compacted = compact(&floats);
assert_eq!(compacted, vec![1.1, 2.2, 3.3, 4.4]);
Determines if a collection is sorted in ascending order.
use lowdash::is_sorted;
let numbers = vec![1, 2, 3, 4, 5];
assert_eq!(is_sorted(&numbers), true);
use lowdash::is_sorted;
let numbers = vec![5, 4, 3, 2, 1];
assert_eq!(is_sorted(&numbers), false);
use lowdash::is_sorted;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
assert_eq!(is_sorted(&people), true);
use lowdash::is_sorted;
let floats = vec![1.1, 2.2, 3.3, 4.4];
assert_eq!(is_sorted(&floats), true);
use lowdash::is_sorted;
let floats = vec![1.1, std::f64::NAN, 3.3];
// Note: Any comparison with NaN returns false, so the slice is not considered sorted.
assert_eq!(is_sorted(&floats), false);
Determines if a collection is sorted in ascending order based on a specified key.
use lowdash::is_sorted_by_key;
let numbers = vec![
(1, "a"),
(2, "b"),
(3, "c"),
(4, "d"),
];
let result = is_sorted_by_key(&numbers, |item| item.0);
assert_eq!(result, true);
use lowdash::is_sorted_by_key;
let numbers = vec![
(1, "a"),
(3, "b"),
(2, "c"),
(4, "d"),
];
let result = is_sorted_by_key(&numbers, |item| item.0);
assert_eq!(result, false);
use lowdash::is_sorted_by_key;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = is_sorted_by_key(&people, |p| p.age);
assert_eq!(result, true);
use lowdash::is_sorted_by_key;
let floats = vec![
(1.1, "apple"),
(2.2, "banana"),
(3.3, "cherry"),
(4.4, "date"),
];
let result = is_sorted_by_key(&floats, |item| item.0);
assert_eq!(result, true);
Inserts elements into a collection at a specified index, handling negative indices and overflow.
use lowdash::splice;
let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99, 100];
let result = splice(&numbers, 2, &elements);
assert_eq!(result, vec![1, 2, 99, 100, 3, 4, 5]);
use lowdash::splice;
let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99, 100];
// Insert at the end
let result = splice(&numbers, 10, &elements);
assert_eq!(result, vec![1, 2, 3, 4, 5, 99, 100]);
use lowdash::splice;
let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99];
// Insert at negative index (-2 means len - 2 = 3)
let result = splice(&numbers, -2, &elements);
assert_eq!(result, vec![1, 2, 3, 99, 4, 5]);
use lowdash::splice;
let numbers = vec![1, 2, 3, 4, 5];
let elements = vec![99];
// Negative index beyond the start, insert at beginning
let result = splice(&numbers, -10, &elements);
assert_eq!(result, vec![99, 1, 2, 3, 4, 5]);
Collects all keys from one or more maps into a single vector.
use lowdash::keys;
use std::collections::HashMap;
let mut map1 = HashMap::new();
map1.insert(1, "a");
map1.insert(2, "b");
let mut map2 = HashMap::new();
map2.insert(3, "c");
map2.insert(4, "d");
let result = keys(&[&map1, &map2]);
assert_eq!(result.len(), 4);
assert!(result.contains(&1));
assert!(result.contains(&2));
assert!(result.contains(&3));
assert!(result.contains(&4));
Collects all unique keys from one or more maps into a single vector.
use lowdash::uniq_keys;
use std::collections::HashMap;
let mut map1 = HashMap::new();
map1.insert("a", 1);
map1.insert("b", 2);
let mut map2 = HashMap::new();
map2.insert("b", 3);
map2.insert("c", 4);
let result = uniq_keys(&[&map1, &map2]);
assert_eq!(result.len(), 3);
assert!(result.contains(&"a"));
assert!(result.contains(&"b"));
assert!(result.contains(&"c"));
Checks if a map contains a specific key.
use lowdash::has_key;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
assert!(has_key(&map, &"a"));
assert!(!has_key(&map, &"c"));
Collects all values from one or more maps into a single vector.
use lowdash::values;
use std::collections::HashMap;
let mut map1 = HashMap::new();
map1.insert("a", 1);
map1.insert("b", 2);
let mut map2 = HashMap::new();
map2.insert("c", 3);
map2.insert("d", 4);
let result = values(&[&map1, &map2]);
assert_eq!(result.len(), 4);
assert!(result.contains(&1));
assert!(result.contains(&2));
assert!(result.contains(&3));
assert!(result.contains(&4));
Collects all unique values from one or more maps into a single vector.
use lowdash::uniq_values;
use std::collections::HashMap;
let mut map1 = HashMap::new();
map1.insert("a", 1);
map1.insert("b", 2);
let mut map2 = HashMap::new();
map2.insert("c", 2);
map2.insert("d", 3);
let result = uniq_values(&[&map1, &map2]);
assert_eq!(result.len(), 3);
assert!(result.contains(&1));
assert!(result.contains(&2));
assert!(result.contains(&3));
Returns a value from a map for a given key, or a fallback value if the key doesn't exist.
use lowdash::value_or;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert_eq!(value_or(&map, &"a", 42), 1);
assert_eq!(value_or(&map, &"b", 42), 42);
Filters a map by applying a predicate to its key-value pairs.
use lowdash::pick_by;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = pick_by(&map, |_, v| *v > 1);
assert_eq!(result.len(), 2);
assert!(result.contains_key("b"));
assert!(result.contains_key("c"));
Filters a map by selecting only the specified keys.
use lowdash::pick_by_keys;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let keys = vec!["a", "c", "d"];
let result = pick_by_keys(&map, &keys);
assert_eq!(result.len(), 2);
assert!(result.contains_key("a"));
assert!(result.contains_key("c"));
Filters a map by selecting only the specified values.
use lowdash::pick_by_values;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let values = vec![1, 3];
let result = pick_by_values(&map, &values);
assert_eq!(result.len(), 2);
assert!(result.contains_key("a"));
assert!(result.contains_key("c"));
Filters a map by omitting key-value pairs that satisfy a predicate.
use lowdash::omit_by;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = omit_by(&map, |_, v| *v > 1);
assert_eq!(result.len(), 1);
assert!(result.contains_key("a"));
assert!(!result.contains_key("b"));
assert!(!result.contains_key("c"));
Filters a map by omitting specified keys.
use lowdash::omit_by_keys;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let keys = vec!["b", "d"];
let result = omit_by_keys(&map, &keys);
assert_eq!(result.len(), 2);
assert!(result.contains_key("a"));
assert!(result.contains_key("c"));
assert!(!result.contains_key("b"));
Filters a map by omitting key-value pairs that have values present in the provided values slice.
use lowdash::omit_by_values;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let values = vec![2, 4];
let result = omit_by_values(&map, &values);
assert_eq!(result.len(), 2);
assert!(result.contains_key("a"));
assert!(result.contains_key("c"));
assert!(!result.contains_key("b"));
Collects all entries from a map into a vector of Entry
structs.
use lowdash::{Entry, entries};
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let result = entries(&map);
let expected = vec![
Entry { key: "a", value: 1 },
Entry { key: "b", value: 2 },
];
let mut sorted_result = result.clone();
sorted_result.sort_by(|a, b| a.key.cmp(&b.key));
let mut sorted_expected = expected.clone();
sorted_expected.sort_by(|a, b| a.key.cmp(&b.key));
assert_eq!(sorted_result, sorted_expected);
Collects all entries from a map into a vector of Entry
structs.
use lowdash::{Entry, to_pairs};
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let result = to_pairs(&map);
let expected = vec![
Entry { key: "a", value: 1 },
Entry { key: "b", value: 2 },
];
let mut sorted_result = result.clone();
sorted_result.sort_by(|a, b| a.key.cmp(&b.key));
let mut sorted_expected = expected.clone();
sorted_expected.sort_by(|a, b| a.key.cmp(&b.key));
assert_eq!(sorted_result, sorted_expected);
Constructs a HashMap
from a slice of Entry
structs.
use lowdash::{Entry, from_entries};
use std::collections::HashMap;
let entries = vec![
Entry { key: "a", value: 1 },
Entry { key: "b", value: 2 },
];
let result = from_entries(&entries);
let mut expected = HashMap::new();
expected.insert("a", 1);
expected.insert("b", 2);
assert_eq!(result.len(), expected.len());
for (key, value) in &expected {
assert_eq!(result.get(key), Some(value));
}
Constructs a HashMap
from a slice of Entry
structs.
use lowdash::{Entry, from_pairs};
use std::collections::HashMap;
let entries = vec![
Entry { key: "a", value: 1 },
Entry { key: "b", value: 2 },
];
let result = from_pairs(&entries);
let mut expected = HashMap::new();
expected.insert("a", 1);
expected.insert("b", 2);
assert_eq!(result.len(), expected.len());
for (key, value) in &expected {
assert_eq!(result.get(key), Some(value));
}
Constructs a HashMap
by inverting the keys and values of the input map.
use lowdash::{invert, Entry};
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let result = invert(&map);
let mut expected = HashMap::new();
expected.insert(1, "a");
expected.insert(2, "b");
expected.insert(3, "c");
assert_eq!(result.len(), expected.len());
for (key, value) in &expected {
assert_eq!(result.get(key), Some(value));
}
Merges multiple maps into a single map. If the same key exists in multiple maps, the value from the last map is used.
use lowdash::assign;
use std::collections::HashMap;
let mut map1 = HashMap::new();
map1.insert("a", 1);
let mut map2 = HashMap::new();
map2.insert("b", 2);
let merged = assign(&[map1, map2]);
assert_eq!(merged.get("a"), Some(&1));
assert_eq!(merged.get("b"), Some(&2));
Transforms the values of a map using a provided function.
use lowdash::map_values;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let transformed = map_values(&map, |&v, _k| v * 10);
assert_eq!(transformed.get("a"), Some(&10));
assert_eq!(transformed.get("b"), Some(&20));
Transforms the keys of a map using a provided function.
use lowdash::map_keys;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let transformed = map_keys(&map, |&v, &k| format!("key_{}", k));
assert_eq!(transformed.get("key_a"), Some(&1));
assert_eq!(transformed.get("key_b"), Some(&2));
Transforms the entries of a map using a provided function.
use lowdash::map_entries;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let transformed = map_entries(&map, |k, v| (k.to_uppercase(), v * 10));
assert_eq!(transformed.get("A"), Some(&10));
assert_eq!(transformed.get("B"), Some(&20));
Transforms the entries of a map into a slice using a provided function.
use lowdash::map_to_slice;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let transformed = map_to_slice(&map, |k, v| format!("{}:{}", k, v));
assert!(transformed.contains(&"a:1".to_string()));
assert!(transformed.contains(&"b:2".to_string()));
Generate a range of integers from 0 to element_num
(exclusive).
If element_num
is negative, generate a range from 0 to -element_num
(exclusive) with a step of -1.
use lowdash::range;
let result = range(5);
assert_eq!(result, vec![0, 1, 2, 3, 4]);
use lowdash::range;
let result = range(-5);
assert_eq!(result, vec![0, -1, -2, -3, -4]);
Generate a range of numbers starting from a given value.
If element_num
is negative, generate a range with a step of -1.
use lowdash::range_from;
let result = range_from(5, 3);
assert_eq!(result, vec![5, 6, 7]);
use lowdash::range_from;
let result = range_from(5, -3);
assert_eq!(result, vec![5, 4, 3]);
Generate a range of numbers from start to end (exclusive) with a specified step.
use lowdash::range_with_steps;
let result = range_with_steps(1, 5, 1);
assert_eq!(result, vec![1, 2, 3, 4]);
use lowdash::range_with_steps;
let result = range_with_steps(5.0, 2.0, -1.0);
assert_eq!(result, vec![5.0, 4.0, 3.0]);
use lowdash::range_with_steps;
let result = range_with_steps(1, 1, 1); // Empty range
assert_eq!(result, Vec::<i32>::new());
Clamps a value between a minimum and maximum value. If the value is less than the minimum, returns the minimum. If the value is greater than the maximum, returns the maximum. Otherwise, returns the value unchanged.
use lowdash::clamp;
assert_eq!(clamp(5, 0, 10), 5); // Value within range
assert_eq!(clamp(-5, 0, 10), 0); // Value below minimum
assert_eq!(clamp(15, 0, 10), 10); // Value above maximum
Calculates the sum of all elements in a collection.
use lowdash::sum;
// Integer sum
assert_eq!(sum(&[1, 2, 3, 4, 5]), 15);
// Float sum
assert_eq!(sum(&[1.1, 2.2, 3.3]), 6.6);
Calculates the sum of values obtained by applying a function to each element in a collection.
use lowdash::sum_by;
let numbers = vec![1, 2, 3, 4];
let result = sum_by(&numbers, |x| x * 2);
assert_eq!(result, 20); // (1*2 + 2*2 + 3*2 + 4*2)
Calculate the product of all elements in a collection. If the collection is empty, returns 1 (multiplicative identity).
use lowdash::product;
// Integer product
let numbers = vec![1, 2, 3, 4, 5];
assert_eq!(product(&numbers), 120);
use lowdash::product;
// Float product
let numbers = vec![1.5, 2.0, 3.0];
assert_eq!(product(&numbers), 9.0);
use lowdash::product;
// Empty collection returns 1
let empty: Vec<i32> = vec![];
assert_eq!(product(&empty), 1);
Calculate the product of values obtained by applying a function to each element in a collection. If the collection is empty, returns 1 (multiplicative identity).
use lowdash::product_by;
let numbers = vec![1, 2, 3, 4];
let result = product_by(&numbers, |x| x * 2);
assert_eq!(result, 384); // (1*2) * (2*2) * (3*2) * (4*2)
use lowdash::product_by;
#[derive(Debug)]
struct Rectangle {
width: f64,
height: f64,
}
let rectangles = vec![
Rectangle { width: 2.0, height: 3.0 },
Rectangle { width: 4.0, height: 5.0 },
];
let total_area = product_by(&rectangles, |r| r.width * r.height);
assert_eq!(total_area, 120.0); // (2*3) * (4*5)
Calculates the arithmetic mean of a collection of numbers. If the collection is empty, returns zero.
use lowdash::mean;
let numbers = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let result = mean(&numbers);
assert_eq!(result, 3.0);
use lowdash::mean;
let numbers = vec![1, 2, 3, 4, 5];
let result = mean(&numbers);
assert_eq!(result, 3);
use lowdash::mean;
let empty: Vec<f64> = vec![];
let result = mean(&empty);
assert_eq!(result, 0.0);
Calculates the mean value of a collection after applying a transformation function to each element.
use lowdash::mean_by;
let objects = vec![(1, 4), (2, 6), (3, 8)];
let mean = mean_by(&objects, |&(x, _)| x as f64);
assert!((mean - 2.0).abs() < f64::EPSILON);
// Calculate mean of y coordinates
let mean_y = mean_by(&objects, |&(_, y)| y as f64);
assert!((mean_y - 6.0).abs() < f64::EPSILON);
Calculates the specified percentile of a collection. The percentile should be a value between 0 and 100. The collection will be sorted before calculation. Uses linear interpolation between closest ranks for non-integer results.
use lowdash::percentile;
let numbers = vec![1, 2, 3, 4, 5];
let result = percentile(&numbers, 50.0);
assert!((result.unwrap() - 3.0).abs() < f64::EPSILON);
use lowdash::percentile;
let numbers = vec![1, 2, 3, 4];
let result = percentile(&numbers, 75.0);
assert!((result.unwrap() - 3.25).abs() < f64::EPSILON);
Calculate the median value of a collection. The median is the 50th percentile of a collection. For collections with an even number of elements, the median is the average of the two middle values. The collection will be sorted before calculation.
use lowdash::median;
let numbers = vec![1, 3, 5, 2, 4];
let result = median(&numbers);
assert!((result.unwrap() - 3.0).abs() < f64::EPSILON);
use lowdash::median;
let numbers = vec![1, 2, 3, 4];
let result = median(&numbers);
assert!((result.unwrap() - 2.5).abs() < f64::EPSILON);
Performs linear interpolation between two values.
use lowdash::interpolate;
let lerp = interpolate(0.0, 10.0);
assert_eq!(lerp(0.5), 5.0);
use lowdash::interpolate;
let lerp = interpolate(-10.0, 10.0);
assert_eq!(lerp(0.25), -5.0);
assert_eq!(lerp(0.75), 5.0);
Finds all permutations of k elements from a collection.
use lowdash::permutation;
let items = vec![1, 2, 3];
let result = permutation(&items, 2);
// Expected permutations: [ [1,2], [1,3], [2,1], [2,3], [3,1], [3,2] ]
assert_eq!(result.len(), 6);
assert!(result.contains(&vec![2, 1]));
Finds all combinations of k elements from a collection.
use lowdash::combination;
let items = vec![1, 2, 3, 4];
let result = combination(&items, 2);
assert_eq!(result.len(), 6);
// One possible combination: [2, 3]
assert!(result.contains(&vec![2, 3]));
Returns the absolute difference between two dates in the specified unit.
use std::time::{SystemTime, Duration};
use lowdash::{duration_between, DurationUnit};
let epoch = SystemTime::UNIX_EPOCH;
let one_year = Duration::from_secs(31_557_600);
let later = epoch + one_year;
// Difference in years
assert_eq!(duration_between(epoch, later, DurationUnit::Years), 1);
let one_day = Duration::from_secs(86_400);
let day_later = epoch + one_day;
// Difference in days
assert_eq!(duration_between(epoch, day_later, DurationUnit::Days), 1);