From c73467caf524a885e73d8d86d91d89a9eced7036 Mon Sep 17 00:00:00 2001 From: "Dr. Carsten Leue" Date: Fri, 26 Jan 2024 10:09:39 +0100 Subject: [PATCH] fix: add WithTime and WithDuration Signed-off-by: Dr. Carsten Leue --- io/generic/io.go | 21 +++++++++++++++++++++ io/io.go | 11 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/io/generic/io.go b/io/generic/io.go index e5a8612..159184f 100644 --- a/io/generic/io.go +++ b/io/generic/io.go @@ -22,6 +22,7 @@ import ( C "github.com/IBM/fp-go/internal/chain" FC "github.com/IBM/fp-go/internal/functor" L "github.com/IBM/fp-go/internal/lazy" + T "github.com/IBM/fp-go/tuple" ) // type IO[A any] = func() A @@ -175,3 +176,23 @@ func MonadFlap[FAB ~func(A) B, GFAB ~func() FAB, GB ~func() B, A, B any](fab GFA func Flap[FAB ~func(A) B, GFAB ~func() FAB, GB ~func() B, A, B any](a A) func(GFAB) GB { return F.Bind2nd(MonadFlap[FAB, GFAB, GB, A, B], a) } + +// WithTime returns an operation that measures the start and end timestamp of the operation +func WithTime[GTA ~func() T.Tuple3[A, time.Time, time.Time], GA ~func() A, A any](a GA) GTA { + return MakeIO[GTA](func() T.Tuple3[A, time.Time, time.Time] { + t0 := time.Now() + res := a() + t1 := time.Now() + return T.MakeTuple3(res, t0, t1) + }) +} + +// WithDuration returns an operation that measures the duration of the operation +func WithDuration[GTA ~func() T.Tuple2[A, time.Duration], GA ~func() A, A any](a GA) GTA { + return MakeIO[GTA](func() T.Tuple2[A, time.Duration] { + t0 := time.Now() + res := a() + t1 := time.Now() + return T.MakeTuple2(res, t1.Sub(t0)) + }) +} diff --git a/io/io.go b/io/io.go index 2d35926..0a9c74f 100644 --- a/io/io.go +++ b/io/io.go @@ -19,6 +19,7 @@ import ( "time" G "github.com/IBM/fp-go/io/generic" + T "github.com/IBM/fp-go/tuple" ) // IO represents a synchronous computation that cannot fail @@ -156,3 +157,13 @@ func Delay[A any](delay time.Duration) func(IO[A]) IO[A] { func After[A any](timestamp time.Time) func(IO[A]) IO[A] { return G.After[IO[A]](timestamp) } + +// WithTime returns an operation that measures the start and end [time.Time] of the operation +func WithTime[A any](a IO[A]) IO[T.Tuple3[A, time.Time, time.Time]] { + return G.WithTime[IO[T.Tuple3[A, time.Time, time.Time]], IO[A]](a) +} + +// WithDuration returns an operation that measures the [time.Duration] +func WithDuration[A any](a IO[A]) IO[T.Tuple2[A, time.Duration]] { + return G.WithDuration[IO[T.Tuple2[A, time.Duration]], IO[A]](a) +}