Skip to content

Instantly share code, notes, and snippets.

@ravisantoshgudimetla
Created December 12, 2017 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravisantoshgudimetla/49336e89a4d5ff371753d424f61828a9 to your computer and use it in GitHub Desktop.
Save ravisantoshgudimetla/49336e89a4d5ff371753d424f61828a9 to your computer and use it in GitHub Desktop.
KVStore with slices
package KVStore
type Item struct {
Key string
Val int
}
type Store []Item
// Checks if the item exists in the store. If the item exists it returns index or else returns -1.
func (s Store) checkIfItemsExistsInStore(key string) int {
for index, item := range s {
if item.Key == key {
return index
}
}
return -1
}
// Get returns value associated with key, if the item exists or else returns -1.
func (s Store) Get(key string) int {
index := s.checkIfItemsExistsInStore(key)
if index != -1 {
return s[index].Val
}
return -1
}
// Put inserts the given item in the store. On success, it returns a 0 and if the item already exists it returns a -1.
func (s Store) Put(item Item) int {
*index := s.checkIfItemsExistsInStore(item.Key)
if index == -1 { // Item doesn't exist. So the item could be safely inserted into store.
s = append(s, item)
return 0
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment