diff --git a/utilities/runAvg/runAvg.go b/utilities/runAvg/runAvg.go index b0de3fd..f832732 100644 --- a/utilities/runAvg/runAvg.go +++ b/utilities/runAvg/runAvg.go @@ -6,11 +6,16 @@ One should implement Val() to be able to use this utility. package runAvg -import "container/list" +import ( + "errors" + "container/list" +) type Interface interface { // Value to use for running average calculation. Val() float64 + // Unique ID + ID() string } type runningAverageCalculator struct { @@ -61,14 +66,42 @@ func (rac *runningAverageCalculator) calculate(data Interface) float64 { return rac.currentSum / float64(rac.window.Len()) } +/* +If element with given ID present in the window, then remove it and return (removeElement, nil). +Else, return (nil, error) +*/ +func (rac *runningAverageCalculator) removeFromWindow(id string) (interface{}, error) { + for element := rac.window.Front(); element != nil; element = element.Next() { + if elementToRemove := element.Value.(Interface); elementToRemove.ID() == id { + rac.window.Remove(element) + return elementToRemove, nil + } + } + return nil, errors.New("Error: Element not found in the window.") +} + // Taking windowSize as a parameter to allow for sliding window implementation. func Calc(data Interface, windowSize int) float64 { rac := getInstance(0.0, 0, windowSize) return rac.calculate(data) } +// Remove element from the window if it is present. +func Remove(id string) (interface{}, error) { + // checking if racSingleton has been instantiated + if racSingleton == nil { + return nil, errors.New("Error: Not instantiated. Please call Init() to instantiate.") + } else { + return racSingleton.removeFromWindow(id) + } +} + // initialize the parameters of the running average calculator func Init() { + // checking to see if racSingleton needs top be instantiated + if racSingleton == nil { + racSingleton = getInstance(0.0, 0, 0) + } // Setting parameters to default values. Could also set racSingleton to nil but this leads to unnecessary overhead of creating // another instance when Calc is called. racSingleton.window.Init()