refactor deltatracker

- embed mutex
- add example function
This commit is contained in:
henrygd
2025-09-16 22:09:46 -04:00
parent 4e0ca7c2ba
commit 1b9e781d45
2 changed files with 32 additions and 15 deletions

View File

@@ -16,7 +16,7 @@ type Numeric interface {
// K is the key type (e.g., int, string).
// V is the value type (e.g., int, int64, float32, float64).
type DeltaTracker[K comparable, V Numeric] struct {
mu sync.RWMutex
sync.RWMutex
current map[K]V
previous map[K]V
}
@@ -31,15 +31,15 @@ func NewDeltaTracker[K comparable, V Numeric]() *DeltaTracker[K, V] {
// Set records the current value for a given ID.
func (t *DeltaTracker[K, V]) Set(id K, value V) {
t.mu.Lock()
defer t.mu.Unlock()
t.Lock()
defer t.Unlock()
t.current[id] = value
}
// Deltas returns a map of all calculated deltas for the current interval.
func (t *DeltaTracker[K, V]) Deltas() map[K]V {
t.mu.RLock()
defer t.mu.RUnlock()
t.RLock()
defer t.RUnlock()
deltas := make(map[K]V)
for id, currentVal := range t.current {
@@ -55,8 +55,8 @@ func (t *DeltaTracker[K, V]) Deltas() map[K]V {
// Delta returns the delta for a single key.
// Returns 0 if the key doesn't exist or has no previous value.
func (t *DeltaTracker[K, V]) Delta(id K) V {
t.mu.RLock()
defer t.mu.RUnlock()
t.RLock()
defer t.RUnlock()
currentVal, currentOk := t.current[id]
if !currentOk {
@@ -73,8 +73,8 @@ func (t *DeltaTracker[K, V]) Delta(id K) V {
// Cycle prepares the tracker for the next interval.
func (t *DeltaTracker[K, V]) Cycle() {
t.mu.Lock()
defer t.mu.Unlock()
t.Lock()
defer t.Unlock()
t.previous = t.current
t.current = make(map[K]V)
}