code refactoring, backend code optimization

This commit is contained in:
2023-10-28 10:32:28 +02:00
parent 2564751405
commit 062e07aa98
7 changed files with 68 additions and 62 deletions

View File

@@ -2,47 +2,19 @@ package rx
import "time"
/*
Package rx contains:
- Definitions for common reactive programming functions/patterns
*/
// ReactiveX inspired debounce function.
//
// Debounce emits a string from the source channel only after a particular
// time span determined a Go Interval
//
// --A--B--CD--EFG-------|>
//
// -t-> |>
// -t-> |> t is a timer tick
// -t-> |>
//
// --A-----C-----G-------|>
func Debounce(interval time.Duration, source chan string, f func(emit string)) {
var item string
timer := time.NewTimer(interval)
for {
select {
case item = <-source:
timer.Reset(interval)
case <-timer.C:
if item != "" {
f(item)
}
}
}
}
// ReactiveX inspired sample function.
//
// Debounce emits the most recently emitted value from the source
// withing the timespan set by the span time.Duration
func Sample[T any](span time.Duration, source chan T, cb func(emit T)) {
timer := time.NewTimer(span)
func Sample[T any](span time.Duration, source chan T, done chan struct{}, fn func(e T)) {
ticker := time.NewTicker(span)
for {
<-timer.C
cb(<-source)
timer.Reset(span)
select {
case <-ticker.C:
fn(<-source)
case <-done:
ticker.Stop()
return
}
}
}