Added functionality to be able to remove elements from the window by providing a unique ID. Also, added another function to the interface that needs to be implemented by all the structs implementing this interface. This function should return a unique ID identifying the object so as to be able to distinguish between multiple instances of the same type.
This commit is contained in:
parent
bd3802ddfd
commit
e0a16da97a
1 changed files with 34 additions and 1 deletions
|
@ -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()
|
||||
|
|
Reference in a new issue