-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Siddarth MSV <[email protected]> Co-authored-by: Aris Tzoumas <[email protected]>
- Loading branch information
1 parent
60bfaa1
commit ea99f1c
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |