From 2ae835e8b2b313de179a5d0c6d668bbcf510d325 Mon Sep 17 00:00:00 2001 From: Nikhil Thomas Date: Sat, 25 Mar 2023 16:08:44 -0400 Subject: [PATCH] Minor Refactor for observer Refactor removeFromSlice function Add an example call to `deregister` in main Signed-off-by: Nikhil Thomas --- observer/item.go | 21 ++++++++++++++------- observer/main.go | 4 ++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/observer/item.go b/observer/item.go index 7130b62..4d4fa6d 100644 --- a/observer/item.go +++ b/observer/item.go @@ -23,7 +23,7 @@ func (i *Item) register(o Observer) { } func (i *Item) deregister(o Observer) { - i.observerList = removeFromslice(i.observerList, o) + i.observerList = removeFromSlice(i.observerList, o) } func (i *Item) notifyAll() { @@ -32,13 +32,20 @@ func (i *Item) notifyAll() { } } -func removeFromslice(observerList []Observer, observerToRemove Observer) []Observer { - observerListLength := len(observerList) +func removeFromSlice(observerList []Observer, observerToRemove Observer) []Observer { + idx := findIndex(observerList, observerToRemove) + if idx == -1 { + return observerList + } + observerList = append(observerList[:idx], observerList[idx+1:]...) + return observerList +} + +func findIndex(observerList []Observer, observerToRemove Observer) int { for i, observer := range observerList { - if observerToRemove.getID() == observer.getID() { - observerList[observerListLength-1], observerList[i] = observerList[i], observerList[observerListLength-1] - return observerList[:observerListLength-1] + if observer.getID() == observerToRemove.getID() { + return i } } - return observerList + return -1 } diff --git a/observer/main.go b/observer/main.go index e022ea9..5b5e131 100644 --- a/observer/main.go +++ b/observer/main.go @@ -11,4 +11,8 @@ func main() { shirtItem.register(observerSecond) shirtItem.updateAvailability() + + shirtItem.deregister(observerFirst) + + shirtItem.updateAvailability() }