Sobes.tech
Junior — Senior

Sequential network requests

livecode

Task condition

Determine what result the program will output. It is necessary to understand how the sequential call of the function fetchByName works, what influence time.Sleep has, and in what form the returned map map[string]int will be formed.

package main

import (
 "context"
 "fmt"
 "math/rand"
 "time"
)

type User struct {
 Name string
}

func main() {
 fmt.Println(Do(context.Background(), []User{{"aaa"}, {"bbb"}, {"ccc"}, {"ddd"}, {"eeee"}}))
}

// fetchByName cannot be changed
func fetchByName(ctx context.Context, userName string) (int, error) {
 time.Sleep(10 * time.Millisecond) // simulate network delay
 return rand.Int() % 100000, nil
}

// all changes should be made in this function
func Do(ctx context.Context, users []User) (map[string]int, error) {
 collected := make(map[string]int)
 for _, u := range users {
  userID, err := fetchByName(ctx, u.Name)
  if err != nil {
   return collected, err
  }
  collected[u.Name] = userID
 }
 return collected, nil
}