Created
December 12, 2017 02:53
-
-
Save ravisantoshgudimetla/49336e89a4d5ff371753d424f61828a9 to your computer and use it in GitHub Desktop.
KVStore with slices
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 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