#FEATURE by exept
authorClaus Gittinger <cg@exept.de>
Tue, 27 Aug 2019 14:13:58 +0200
changeset 24668 428fc2bc187b
parent 24667 fdbe0a558746
child 24669 7540ae9bf32a
#FEATURE by exept class: Bag added: #valuesAndCountsDetect:ifNone:
Bag.st
--- a/Bag.st	Tue Aug 27 11:05:55 2019 +0200
+++ b/Bag.st	Tue Aug 27 14:13:58 2019 +0200
@@ -432,6 +432,36 @@
     "Modified: 1.3.1996 / 21:42:44 / cg"
 !
 
+valuesAndCountsDetect:aTwoArgBlock ifNone:exceptionValue
+    "evaluate the block for all distinct elements in the collection,
+     passing both the element and the occurrence count as arguments.
+     If any returns true, return an association consisting of value and occurrence count.
+     If not, return the value from exceptionValue.
+
+     WARNING: do not add/remove elements while iterating over the receiver.
+              Iterate over a copy to do this."
+
+    |collected|
+
+    collected := OrderedCollection new.
+    self valuesAndCountsDo:[:eachValue :eachCount|
+        (aTwoArgBlock value:eachValue value:eachCount) ifTrue:[
+            ^ eachValue -> eachCount
+        ].
+    ].
+    ^ exceptionValue value
+
+    "
+     #(10 20 20 30 40) asBag
+        valuesAndCountsDetect:[:eachValue :eachCount | eachCount > 1]
+        ifNone:nil     
+
+     #(10 20 20 30 40) asBag
+        valuesAndCountsDetect:[:eachValue :eachCount | eachCount > 3]
+        ifNone:nil     
+    "
+!
+
 valuesAndCountsDo:aTwoArgBlock
     "evaluate the block for all distinct elements in the collection,
      passing both the element and the occurrence count as arguments.