Tuesday, 21 March 2017

CodeWars - Greet Developers

Greet Developers

Another good one easy one from Piotr.

After the last exercise I went straight for the .forEach method. I was pretty sure I could just obj.greetdevelopers = [...] and so it was.

Initially I tried to use this.firstName and this.language but that didn’t work and it seems obvious to me now because at the time this is invoked it refers to the object in which the function greetDevelopers’s execution context is created. In this case the global object, I think.

So I replaced it with obj.

Here’s the code I ended up with:

function greetDevelopers(list) {
    list.forEach ((obj) => obj.greeting = "Hi " + obj.firstName + ", what do you like the most about " + obj.language +"?");    
    return list;
}

The function acts on each object in turn, changing it. The list object (and array) is not changed per se - it is identical at the start and end - but each object element within it has been amended.

I couldn’t get the => to work properly. Need to find out about that.

Done.

Other Solutions

Looking at the existing solutions on CodeWars, I notice the top differ slightly from mine:

    function greetDevelopers(list) {
      return list.map(x => Object.assign({}, x, {
        greeting: `Hi ${x.firstName}, what do you like the most about ${x.language}?`
      }))
    }

Object.assign({}, x, {...})) and the ${ } escapes (or whatever you want to call them)…