Skip to content

Instantly share code, notes, and snippets.

@rcrowley
Created July 23, 2014 00:59
Show Gist options
  • Save rcrowley/e4b7f4a04bfed3157274 to your computer and use it in GitHub Desktop.
Save rcrowley/e4b7f4a04bfed3157274 to your computer and use it in GitHub Desktop.
Least-Recently Accessed
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
}
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