From 9dabd87f069b1fe22e16f4640dab394a24babc31 Mon Sep 17 00:00:00 2001 From: Farhan Khan Date: Wed, 3 Feb 2021 00:07:51 +0000 Subject: [PATCH] forgot to use commit uniquefifo.go --- uniquefifo.go | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 uniquefifo.go diff --git a/uniquefifo.go b/uniquefifo.go new file mode 100644 index 0000000..15fc3bc --- /dev/null +++ b/uniquefifo.go @@ -0,0 +1,82 @@ +package main + +import ( + "sync" +) + +type UniqueFifo struct { + slice []string + mu sync.Mutex + size int +} + + +func newUniqueFifo(size int) *UniqueFifo { + q := UniqueFifo{} + q.slice = make([]string, 0) + q.size = size + return &q +} + +func (q *UniqueFifo) Add(v string) bool { + ret := false + if len(q.slice) == 0 { + q.slice = append(q.slice, v) +//logDebug.Print("Condition 1 for ", v) + ret = false + } else { + i := q.Contains(v) + if i != -1 { + q.Remove(i) +//logDebug.Print("Condition 2 for ", v) + ret = true + } else { +//logDebug.Print("Condition 3 for ", v) + ret = false + } + q.slice = append(q.slice, "") + copy(q.slice[1:], q.slice) + q.slice[0] = v + if len(q.slice) <= q.size { + q.slice = q.slice[:len(q.slice)] + } else { + q.slice = q.slice[:q.size] + } + } + + return ret +} + +func (q *UniqueFifo) Remove(r int) { + f := q.slice[:r] + e := q.slice[r+1:] + q.slice = f + q.slice = append(q.slice, e...) +} + + +func (q *UniqueFifo) Contains(v string) int { + for i, val := range q.slice { + if val == v { + return i + } + } + return -1 +} + +/* +func main() { + u := newUniqueFifo(3) + u.Add("First") + u.Add("First") + fmt.Println(u) + u.Add("Second") + fmt.Println(u) + u.Add("First") + fmt.Println(u) + u.Add("Third") + fmt.Println(u) + u.Add("Fourth") + fmt.Println(u) +} +*/