Friendly Challenge for Developers

dev-challenges
thebotguys-tavern

#1

Hello folks,
today I have a challenge for you
try to translate the following Javascript code into GO and get tipped
Here is the code

const a = await fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => json.sort((a, b) => a.username.localeCompare(b.username)
        .map(a => a.test = "yay"))
    .then(console.log)

Hope you will all have fun!

See ya

NOTE: there are multiple solutions, the cleanest one will have honour and fame.


#2

I received some solutions in private, but they did not satisfy me:
Here is the correct solution

resp, err := http.defaultClient.Do("GET", "https://jsonplaceholder.typicode.com/users")
if err != nil {
    handleError(err) // handles errors separately
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
    handleError(err) // handles errors separately
}
defer resp.Body.Close()

type APIResponse struct {
    // definition of user from API omitted
    // but we add Test field as json private
    Test string `json:"-"`
}

var response []APIResponse
err := json.Unmarshal(content, &response)
if err != nil {
    handleError(err) // handles errors separately
}

//sort
sort.Slice(response, func (i,j int) bool {
    return strings.Compare(a.Username, b.Username) < 0
})

// now we apply map function and print
for _, val := range response {
    a.Test = "yay"
}

// print
fmt.Println(response)

Wanna learn Go Language? Contact me on discord or slack @thebotguy


#3