lowdash/first_or_empty.rs
1use crate::first::first;
2
3/// Returns the first item from the collection.
4/// If the collection is empty, returns the default value of `T`.
5///
6/// # Arguments
7/// * `collection` - A slice of items.
8///
9/// # Returns
10/// * `T` - The first item in the collection.
11/// If the collection is empty, returns `T::default()`.
12///
13/// # Examples
14/// ```rust
15/// use lowdash::first_or_empty;
16///
17/// let numbers = vec![1, 2, 3];
18/// let first_num = first_or_empty(&numbers);
19/// assert_eq!(first_num, 1);
20///
21/// let empty: Vec<i32> = vec![];
22/// let first_num = first_or_empty(&empty);
23/// assert_eq!(first_num, 0); // i32::default() is 0
24/// ```
25///
26/// ```rust
27/// use lowdash::first_or_empty;
28///
29/// #[derive(Debug, PartialEq, Clone, Default)]
30/// struct Person {
31/// name: String,
32/// age: u32,
33/// }
34///
35/// let people = vec![
36/// Person { name: "Alice".to_string(), age: 25 },
37/// Person { name: "Bob".to_string(), age: 30 },
38/// ];
39///
40/// let first_person = first_or_empty(&people);
41/// assert_eq!(first_person, Person { name: "Alice".to_string(), age: 25 });
42///
43/// let empty_people: Vec<Person> = vec![];
44/// let first_person = first_or_empty(&empty_people);
45/// assert_eq!(first_person, Person::default());
46/// ```
47pub fn first_or_empty<T>(collection: &[T]) -> T
48where
49 T: Clone + Default,
50{
51 let (item, _) = first(collection);
52 item
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[derive(Debug, PartialEq, Clone, Default)]
60 struct Item {
61 name: String,
62 value: i32,
63 }
64
65 #[test]
66 fn test_first_or_empty_with_non_empty_collection() {
67 let collection = vec![1, 2, 3];
68 let first = first_or_empty(&collection);
69 assert_eq!(first, 1);
70 }
71
72 #[test]
73 fn test_first_or_empty_with_empty_collection() {
74 let collection: Vec<i32> = vec![];
75 let first = first_or_empty(&collection);
76 assert_eq!(first, 0); // i32::default() is 0
77 }
78
79 #[test]
80 fn test_first_or_empty_with_structs() {
81 let item1 = Item {
82 name: "Item1".to_string(),
83 value: 10,
84 };
85 let item2 = Item {
86 name: "Item2".to_string(),
87 value: 20,
88 };
89 let collection = vec![item1.clone(), item2.clone()];
90 let first = first_or_empty(&collection);
91 assert_eq!(first, item1);
92 }
93
94 #[test]
95 fn test_first_or_empty_with_single_item() {
96 let collection = vec![42];
97 let first = first_or_empty(&collection);
98 assert_eq!(first, 42);
99 }
100
101 #[test]
102 fn test_first_or_empty_with_custom_default() {
103 let collection: Vec<Item> = vec![];
104 let first = first_or_empty(&collection);
105 assert_eq!(first, Item::default());
106 }
107
108 #[test]
109 fn test_first_or_empty_with_partial_empty_struct() {
110 let item = Item {
111 name: "Partial".to_string(),
112 value: 0,
113 };
114 let collection = vec![item.clone()];
115 let first = first_or_empty(&collection);
116 assert_eq!(first, item);
117 }
118}