Skip to content

Instantly share code, notes, and snippets.

@toVersus
Created April 17, 2018 14:20
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 toVersus/dd1b770999d7c7811a38ea23682ffd96 to your computer and use it in GitHub Desktop.
Save toVersus/dd1b770999d7c7811a38ea23682ffd96 to your computer and use it in GitHub Desktop.
[Language Processing 100 Essentials] #62: Iterate to count the number of artists in specified area
package main
import (
"flag"
"fmt"
"os"
"github.com/go-redis/redis"
)
// TODO: improve O(n) implementation...
// https://stackoverflow.com/questions/17193176/searching-in-values-of-a-redis-db
func main() {
var area string
flag.StringVar(&area, "area", "", "specify the area")
flag.Parse()
client, err := newRedisClient()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
keys, err := client.Keys("*").Result()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
count := 0
for _, key := range keys {
val, err := client.Get(key).Result()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if val != area {
continue
}
count++
}
fmt.Printf("found %d keys\n", count)
}
func newRedisClient() (*redis.Client, error) {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
pong, err := client.Ping().Result()
if err != nil {
return nil, fmt.Errorf("could not connect to redis\n %s", err)
}
fmt.Println(pong, err)
return client, nil
}
package main
import (
"fmt"
"testing"
"github.com/go-test/deep"
)
var countArtistsTests = []struct {
name string
area string
want int
}{
{
name: "should count the number of artists correctly",
area: "Minneapolis–Saint Paul",
// actual count is 9 but that artist name is duplicated and overwritten by the one in another area.
want: 8,
},
{
name: "should return zero",
area: "null",
want: 0,
},
}
func TestGetKeyVal(t *testing.T) {
for _, testcase := range countArtistsTests {
t.Log(testcase.name)
client, err := newRedisClient()
if err != nil {
t.Error(err)
}
keys, err := client.Keys("*").Result()
if err != nil {
t.Error(err)
}
count := 0
for _, key := range keys {
val, err := client.Get(key).Result()
if err != nil {
t.Error(err)
}
if val != testcase.area {
continue
}
fmt.Println(key)
count++
}
if diff := deep.Equal(count, testcase.want); diff != nil {
t.Error(diff)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment