From 29a4df0a1c54b765e32d9c5dd6c1bbea3446bed3 Mon Sep 17 00:00:00 2001 From: Siddarth MSV Date: Wed, 19 Apr 2023 10:59:51 +0530 Subject: [PATCH 1/2] package ro: memoize --- ro/ro.go | 14 ++++++++++++++ ro/ro_test.go | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 ro/ro.go create mode 100644 ro/ro_test.go diff --git a/ro/ro.go b/ro/ro.go new file mode 100644 index 00000000..cbebf38c --- /dev/null +++ b/ro/ro.go @@ -0,0 +1,14 @@ +package ro + +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 + } +} diff --git a/ro/ro_test.go b/ro/ro_test.go new file mode 100644 index 00000000..8348b431 --- /dev/null +++ b/ro/ro_test.go @@ -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() + } +} From 08567b6844d1e7037b0b8aa2d4ee2d50422470d2 Mon Sep 17 00:00:00 2001 From: "siddarth.msv" <82795818+Sidddddarth@users.noreply.github.com> Date: Wed, 19 Apr 2023 11:41:54 +0530 Subject: [PATCH 2/2] Update ro/ro.go Co-authored-by: Aris Tzoumas --- ro/ro.go | 1 + 1 file changed, 1 insertion(+) diff --git a/ro/ro.go b/ro/ro.go index cbebf38c..bcab056b 100644 --- a/ro/ro.go +++ b/ro/ro.go @@ -1,5 +1,6 @@ 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