Last active
August 29, 2015 14:22
-
-
Save HelloGrayson/202619df841c0ccdab73 to your computer and use it in GitHub Desktop.
Golang concurrency challenge: make this program finish in 1 second instead of 3.
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 main | |
import ( | |
"time" | |
"fmt" | |
) | |
// | |
// Challenge: modify readAllFromOrgs so that the program finishes | |
// in 1 second instead of 3. | |
// | |
func main() { | |
repos := readAllFromOrgs([]string{"microsoft", "yahoo", "google"}) | |
fmt.Println(repos) | |
} | |
// Our own type representing a github repository | |
type Repo struct { | |
Name string | |
} | |
// | |
// Our unoptimized gateway function that calls the Github API. | |
// This function should be modified such that the call to | |
// "githubApiListReposByOrg()" is made in parallel. Note that you | |
// cannot change this function signature at all. | |
// | |
func readAllFromOrgs(orgs []string) []Repo { | |
// starting with an empty array of repos | |
repos := []Repo{} | |
// make calls to the Github API for each Org provided | |
for i := range orgs { | |
fmt.Println(orgs[i]) | |
github_repos := githubApiListReposByOrg() | |
// hydrate array of Repository from github.Repository | |
for r := range github_repos { | |
repos = append( | |
repos, | |
Repo{Name: github_repos[r].FullName}, | |
) | |
} | |
} | |
return repos | |
} | |
// | |
// BELOW IS LIBRARY CODE, YOU CANNOT EDIT IT. | |
// | |
type GithubRepo struct { | |
FullName string | |
} | |
// Stubbed Github API call. Regularly, this call looks like: | |
// client.Repositories.ListByOrg(orgs[i], opt). | |
func githubApiListReposByOrg() []GithubRepo { | |
time.Sleep(1000 * time.Millisecond) | |
r1 := GithubRepo{FullName: "r1"} | |
r2 := GithubRepo{FullName: "r2"} | |
return []GithubRepo{r1, r2} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment