Skip to content

Commit

Permalink
fix: add WithTime and WithDuration
Browse files Browse the repository at this point in the history
Signed-off-by: Dr. Carsten Leue <carsten.leue@de.ibm.com>
  • Loading branch information
CarstenLeue committed Jan 26, 2024
1 parent ca60676 commit c73467c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions io/generic/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
})
}
11 changes: 11 additions & 0 deletions io/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}

0 comments on commit c73467c

Please sign in to comment.