#FEATURE by stefan
authorStefan Vogel <sv@exept.de>
Wed, 09 Oct 2019 11:17:07 +0200
changeset 24824 46b44bdbc5d2
parent 24823 ff0c79c82ca2
child 24825 363db976dea9
#FEATURE by stefan class: SequenceableCollection added: #upToOrSelf: the code in this method was used at 5 different places
SequenceableCollection.st
--- a/SequenceableCollection.st	Sat Oct 05 14:59:13 2019 +0200
+++ b/SequenceableCollection.st	Wed Oct 09 11:17:07 2019 +0200
@@ -4815,6 +4815,44 @@
     "
 !
 
+upToOrSelf:anElement
+    "return a new collection consisting of the receiver's elements upTo
+     (but excluding) anElement.
+     If anElement is not in the receiver, return myself (not a copy!!).
+     See also #restAfter:  , #copyFrom:index.
+
+     This is similar to #upTo: but avoids garbage if anElement is not
+     present in the collection and a copy of the collection is not needed."
+
+    |pos|
+
+    pos := self indexOf:anElement.
+    pos == 0 ifTrue:[^ self].
+
+    ^ self copyFrom:1 to:(pos - 1)
+
+    "
+     #(1 2 3 4 5 6 7 8 9) upToOrSelf:5
+     'hello world' upToOrSelf:Character space
+     #(9 8 7 6 5 4 3 2 1) asSortedCollection upToOrSelf:5
+     '1234.5678' upToOrSelf:$.
+     '1234'      upToOrSelf:$.
+     '.'      upToOrSelf:$.
+
+
+     raises an error:
+
+     (Dictionary new
+        at:#foo put:'foo';
+        at:#bar put:'bar';
+        at:#baz put:'baz';
+        yourself) upToOrSelf:#bar
+
+    "
+
+    "Created: / 09-10-2019 / 10:57:04 / Stefan Vogel"
+!
+
 upToSeparator
     "Return the next elements up to but not including the next separator.
      The next read will return the separator.