Skip to content

Commit

Permalink
feat: package ro - memoize (#30)
Browse files Browse the repository at this point in the history
Co-authored-by: Siddarth MSV <siddarthmsv@gmail.com>
Co-authored-by: Aris Tzoumas <atzoumas@rudderstack.com>
  • Loading branch information
3 people committed Apr 19, 2023
1 parent 60bfaa1 commit ea99f1c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions ro/ro.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ro

// Memoize stores the execution result of the provided function in-memory during the first call and uses it as a return value for subsequent calls
func Memoize[R any](f func() R) func() R {
var result R
var called bool
return func() R {
if called {
return result
}
result = f()
called = true
return result
}
}
23 changes: 23 additions & 0 deletions ro/ro_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package ro

import (
"testing"
)

func TestMemoize(t *testing.T) {
var count int
f := func() int {
count++
return count
}
g := Memoize(f)
if g() != 1 {
t.Fail()
}
if g() != 1 {
t.Fail()
}
if g() != 1 {
t.Fail()
}
}

0 comments on commit ea99f1c

Please sign in to comment.