Skip to content

Commit 1ea4d60

Browse files
Merge pull request #874 from amirhoseinsalimi/feature/collection-min
feat: add `Collection.min` method
2 parents 11fd4d9 + 3bc3406 commit 1ea4d60

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/masoniteorm/collection/Collection.py

+20
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,26 @@ def max(self, key=None):
109109
except (TypeError, ValueError):
110110
pass
111111
return result
112+
113+
def min(self, key=None):
114+
"""Returns the min of the items.
115+
116+
If a key is given it will return the min of all the values of the key.
117+
118+
Keyword Arguments:
119+
key {string} -- The key to use to find the min of all the values of that key. (default: {None})
120+
121+
Returns:
122+
int -- Returns the min.
123+
"""
124+
result = 0
125+
items = self._get_value(key) or self._items
126+
127+
try:
128+
return min(items)
129+
except (TypeError, ValueError):
130+
pass
131+
return result
112132

113133
def chunk(self, size: int):
114134
"""Chunks the items.

tests/collection/test_collection.py

+18
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,24 @@ def test_max(self):
185185
collection = Collection([{"batch": 1}, {"batch": 1}])
186186
self.assertEqual(collection.max("batch"), 1)
187187

188+
def test_min(self):
189+
collection = Collection([1, 1, 2, 4])
190+
self.assertEqual(collection.min(), 1)
191+
192+
collection = Collection(
193+
[
194+
{"name": "Corentin All", "age": 1},
195+
{"name": "Corentin All", "age": 2},
196+
{"name": "Corentin All", "age": 3},
197+
{"name": "Corentin All", "age": 4},
198+
]
199+
)
200+
self.assertEqual(collection.min("age"), 1)
201+
self.assertEqual(collection.min(), 0)
202+
203+
collection = Collection([{"batch": 1}, {"batch": 1}])
204+
self.assertEqual(collection.min("batch"), 1)
205+
188206
def test_count(self):
189207
collection = Collection([1, 1, 2, 4])
190208
self.assertEqual(collection.count(), 4)

0 commit comments

Comments
 (0)