#FEATURE by cg
authorClaus Gittinger <cg@exept.de>
Tue, 21 May 2019 11:49:58 +0200
changeset 24128 4029e964d0f1
parent 24127 ce2a0e462ff0
child 24129 ca2d5b78d628
#FEATURE by cg class: OrderedCollection added: #removeLastIfAbsent:
OrderedCollection.st
--- a/OrderedCollection.st	Sat May 18 10:14:18 2019 +0200
+++ b/OrderedCollection.st	Tue May 21 11:49:58 2019 +0200
@@ -1337,6 +1337,39 @@
     "Modified: 12.4.1996 / 13:39:12 / cg"
 !
 
+removeLastIfAbsent:exceptionValue
+    "remove the last element from the collection.
+     Return the removed element or the value from exceptionValue if empty.
+     Destructive: modifies the receiver"
+
+    |anObject
+     idx "{ Class: SmallInteger }" |
+
+    idx := lastIndex.
+    firstIndex > idx ifTrue:[
+        "collection is empty"
+        ^ exceptionValue value.
+    ].
+    anObject := contentsArray basicAt:idx.
+
+    "/ nil it (helps GC)
+    contentsArray basicAt:idx put:nil.
+    lastIndex := idx := idx - 1.
+
+    firstIndex > idx ifTrue:[
+        "reset to avoid ever growing"
+        firstIndex := 1.
+        lastIndex := 0
+    ].
+    ^ anObject
+
+    "
+     OrderedCollection new removeLastIfAbsent:nil
+    "
+
+    "Created: / 21-05-2019 / 08:47:55 / Claus Gittinger"
+!
+
 reset
     "logically remove all elements from the collection.
      That's almost the same as #removeAll, but keeps the contentsArray.