#FEATURE by cg
authorClaus Gittinger <cg@exept.de>
Wed, 13 Feb 2019 19:21:15 +0100
changeset 23730 79e4b8567d49
parent 23729 772ddbedfb9d
child 23731 ab6d034fbaa3
#FEATURE by cg class: Collection added: #max: #min:
Collection.st
--- a/Collection.st	Wed Feb 13 18:09:57 2019 +0100
+++ b/Collection.st	Wed Feb 13 19:21:15 2019 +0100
@@ -297,6 +297,8 @@
     ^ self newWithSize:n
 ! !
 
+
+
 !Collection class methodsFor:'Signal constants'!
 
 emptyCollectionSignal
@@ -358,6 +360,7 @@
     ^ self == Collection
 ! !
 
+
 !Collection methodsFor:'Compatibility-ANSI'!
 
 identityIncludes:anObject
@@ -367,6 +370,7 @@
     ^ self includesIdentical:anObject.
 ! !
 
+
 !Collection methodsFor:'Compatibility-Squeak'!
 
 , aCollection
@@ -527,6 +531,7 @@
     ^ self ifEmpty:ifEmptyValue ifNotEmpty:ifNotEmptyValue
 ! !
 
+
 !Collection methodsFor:'accessing'!
 
 anElement
@@ -5774,6 +5779,30 @@
     "Modified: / 11-07-2010 / 17:05:25 / cg"
 !
 
+max:comparator
+    "return the maximum value in the receiver collection,
+     using comparator to compare elements.
+     The argument comparator is a 2-arg block returning true if the first arg is less than the second.
+     Raises an error if the receiver is empty."
+
+    ^ self
+        fold:[:maxSoFar :each |
+            (comparator value:maxSoFar value:each)
+                ifTrue:[each]
+                ifFalse:[maxSoFar]
+        ]
+
+    "
+     find the largest element (same as max without comparator):
+         #(15 1 -20 -9 10 5) max:[:a :b | a < b]
+
+     find the element which has the largest abs value:
+         #(15 1 -20 -9 10 5) max:[:a :b | a abs < b abs]
+    "
+
+    "Created: / 13-02-2019 / 19:16:54 / Claus Gittinger"
+!
+
 maxApplying:aBlock
     "return the maximum value from applying aBlock to each element in the receiver collection,
      using aBlock to compare elements.
@@ -5829,6 +5858,30 @@
     "Modified: / 11-07-2010 / 17:06:38 / cg"
 !
 
+min:comparator
+    "return the minimum value in the receiver collection,
+     using comparator to compare elements.
+     The argument comparator is a 2-arg block returning true if the first arg is less than the second.
+     Raises an error if the receiver is empty."
+
+    ^ self
+        fold:[:minSoFar :each |
+            (comparator value:each value:minSoFar)
+                ifTrue:[each]
+                ifFalse:[minSoFar]
+        ]
+
+    "
+     find the smallest element (same as min without comparator):
+         #(15 1 -9 10 5) min:[:a :b | a < b]
+     
+     find the element which has the smallest abs value:
+         #(15 1 -9 10 5) min:[:a :b | a abs < b abs]
+    "
+
+    "Created: / 13-02-2019 / 19:15:58 / Claus Gittinger"
+!
+
 minApplying:aBlock
     "return the minimum value from applying aBlock to each element in the receiver collection,
      using aBlock to compare elements.
@@ -6479,6 +6532,7 @@
     ^ aVisitor visitCollection:self with:aParameter
 ! !
 
+
 !Collection class methodsFor:'documentation'!
 
 version