#FEATURE by stefan expecco_18_1_0wa1
authorStefan Vogel <sv@exept.de>
Tue, 03 Jul 2018 23:38:44 +0200
changeset 23189 15ea23cfead5
parent 23188 709c48bf557e
child 23190 611aa626a4a4
#FEATURE by stefan class: Set added: #addOrReplace:
Set.st
--- a/Set.st	Tue Jul 03 11:09:55 2018 +0200
+++ b/Set.st	Tue Jul 03 23:38:44 2018 +0200
@@ -381,6 +381,48 @@
     "Modified: 30.1.1997 / 14:58:08 / cg"
 !
 
+addOrReplace:anObject
+    "add the argument, anObject to the receiver.
+     If it is already included, replace it by anObject.
+     Return nil, if anObject was not present in the receiver, 
+     otherwise the element that has been replaced.
+
+     WARNING: do not add elements while iterating over the receiver.
+              Iterate over a copy to do this."
+
+    |key index "{ Class: SmallInteger }" existingKey|
+
+    anObject isNil ifTrue:[
+        key := NilEntry.
+    ] ifFalse:[
+        key := anObject.
+    ].
+
+    index := self findKeyOrNil:key.
+    existingKey := keyArray basicAt:index.
+    keyArray basicAt:index put:key.
+    existingKey isNil ifTrue:[
+        "/ not already there
+        tally := tally + 1.
+        self possiblyGrow.
+    ].
+    ^ existingKey
+
+    "
+        Note that 1 is replaced by 1.0:
+
+        self new 
+                addOrReplace:1;
+                addOrReplace:2;
+                addOrReplace:nil;
+                addOrReplace:1.0;
+                yourself
+    "
+
+    "Created: / 03-07-2018 / 19:13:58 / Stefan Vogel"
+    "Modified (comment): / 03-07-2018 / 23:38:13 / Stefan Vogel"
+!
+
 clearContents
     "remove all elements from the receiver, but do not resize the underlying keyArray.
      Returns the receiver.
@@ -844,6 +886,7 @@
 ! !
 
 
+
 !Set methodsFor:'obsolete set operations'!
 
 + aCollection
@@ -1290,6 +1333,7 @@
     ^ tally
 ! !
 
+
 !Set methodsFor:'searching'!
 
 findFirst:aBlock ifNone:exceptionValue