Commit 4748519

mo khan <mo.khan@gmail.com>
2019-12-08 19:51:18
learn about go routines
1 parent e67ebfe
check_websites.go
@@ -0,0 +1,25 @@
+package main
+
+type WebsiteChecker func(string) bool
+type result struct {
+	string
+	bool
+}
+
+func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
+	results := make(map[string]bool)
+	resultChannel := make(chan result)
+
+	for _, url := range urls {
+		go func(u string) {
+			resultChannel <- result{u, wc(u)}
+		}(url)
+	}
+
+	for i := 0; i < len(urls); i++ {
+		result := <-resultChannel
+		results[result.string] = result.bool
+	}
+
+	return results
+}
check_websites_test.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+	"reflect"
+	"testing"
+)
+
+func mockWebsiteChecker(url string) bool {
+	if url == "https://www.example.com" {
+		return false
+	}
+	return true
+}
+
+func TestCheckWebsites(t *testing.T) {
+	websites := []string{
+		"https://www.google.com",
+		"https://www.example.com",
+	}
+
+	want := map[string]bool{
+		"https://www.google.com":  true,
+		"https://www.example.com": false,
+	}
+
+	got := CheckWebsites(mockWebsiteChecker, websites)
+
+	if !reflect.DeepEqual(want, got) {
+		t.Fatalf("Wanted %v got %v", want, got)
+	}
+}