mirror of
https://github.com/IBM/fp-go.git
synced 2025-08-10 22:31:32 +02:00
fix: add consistent Delay and After functions to IO
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
This commit is contained in:
@@ -133,6 +133,29 @@ func Delay[GA ~func() A, A any](delay time.Duration) func(GA) GA {
|
||||
}
|
||||
}
|
||||
|
||||
func after(timestamp time.Time) func() {
|
||||
return func() {
|
||||
// check if we need to wait
|
||||
current := time.Now()
|
||||
if current.Before(timestamp) {
|
||||
time.Sleep(timestamp.Sub(current))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// After creates an operation that passes after the given timestamp
|
||||
func After[GA ~func() A, A any](timestamp time.Time) func(GA) GA {
|
||||
aft := after(timestamp)
|
||||
return func(ga GA) GA {
|
||||
return MakeIO[GA](func() A {
|
||||
// wait as long as necessary
|
||||
aft()
|
||||
// execute after wait
|
||||
return ga()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Now returns the current timestamp
|
||||
func Now[GA ~func() time.Time]() GA {
|
||||
return MakeIO[GA](time.Now)
|
||||
|
10
io/io.go
10
io/io.go
@@ -146,3 +146,13 @@ func MonadFlap[B, A any](fab IO[func(A) B], a A) IO[B] {
|
||||
func Flap[FAB ~func(A) B, GFAB ~func() FAB, GB ~func() B, A, B any](a A) func(IO[func(A) B]) IO[B] {
|
||||
return G.Flap[func(A) B, IO[func(A) B], IO[B], A, B](a)
|
||||
}
|
||||
|
||||
// Delay creates an operation that passes in the value after some delay
|
||||
func Delay[A any](delay time.Duration) func(IO[A]) IO[A] {
|
||||
return G.Delay[IO[A]](delay)
|
||||
}
|
||||
|
||||
// After creates an operation that passes after the given timestamp
|
||||
func After[A any](timestamp time.Time) func(IO[A]) IO[A] {
|
||||
return G.After[IO[A]](timestamp)
|
||||
}
|
||||
|
Reference in New Issue
Block a user