Created
July 23, 2014 00:59
-
-
Save rcrowley/e4b7f4a04bfed3157274 to your computer and use it in GitHub Desktop.
Least-Recently Accessed
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
package lra | |
// LRA is a fixed-size cache which expires the least-recently added string. | |
type LRA struct { | |
i int | |
m map[string]struct{} | |
ss []string | |
} | |
func NewLRA(n int) *LRA { | |
return &LRA{ | |
m: make(map[string]struct{}), | |
ss: make([]string, n), | |
} | |
} | |
func (lra *LRA) Add(s string) { | |
lra.m[s] = struct{}{} | |
delete(lra.m, lra.ss[lra.i]) | |
lra.ss[lra.i] = s | |
lra.i = (lra.i + 1) % len(lra.ss) | |
} | |
func (lra *LRA) Has(s string) bool { | |
_, ok := lra.m[s] | |
return ok | |
} |
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
package lra | |
import "testing" | |
func TestLRA1(t *testing.T) { | |
lra := NewLRA(2) | |
lra.Add("foo") | |
if !lra.Has("foo") { | |
t.Fatal("foo") | |
} | |
if lra.Has("bar") { | |
t.Fatal("bar") | |
} | |
if lra.Has("baz") { | |
t.Fatal("baz") | |
} | |
} | |
func TestLRA2(t *testing.T) { | |
lra := NewLRA(2) | |
lra.Add("foo") | |
lra.Add("bar") | |
if !lra.Has("foo") { | |
t.Fatal("foo") | |
} | |
if !lra.Has("bar") { | |
t.Fatal("bar") | |
} | |
if lra.Has("baz") { | |
t.Fatal("baz") | |
} | |
} | |
func TestLRA3(t *testing.T) { | |
lra := NewLRA(2) | |
lra.Add("foo") | |
lra.Add("bar") | |
lra.Add("baz") | |
if lra.Has("foo") { | |
t.Fatal("foo") | |
} | |
if !lra.Has("bar") { | |
t.Fatal("bar") | |
} | |
if !lra.Has("baz") { | |
t.Fatal("baz") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment