0

Today I was doing checking some code in GitHub and after seeing a function that I thought was wrong I ended playing with map function to try it.

This is the subset of code that in my opinion was wrong but is working perfectly. As there is no return I thought the map would not return anything. (state = [{ text: text, completed: completed }] }

case TOGGLE_TODO:
    return state.map(todo =>
    (todo.id === action.id)
      ? {...todo, completed: !todo.completed}
      : todo
     )

I have done several tries but I do not get to emulate that functionality without adding a return to the map function.

Test 1:

var arrO = [ {n:0,t:1}, {n:1,t:2}, {n:2,t:3} ];
arrO2 = arrO.map( (obj, index) => {(index === 0)?{...obj, t:obj.t*10}:obj})

The content of arrO2 is this:

0: undefined
1: undefined
2: undefined
length: 3

Test 2:

arrO3 = arrO.map( (obj, index) => { var res = null; (index === 0)? res = {...obj,  t:obj.t*10} : res = obj ; return res  })

The content of arrO3 is this:

0: {n: 0, t: 10}
1: {n: 1, t: 2}
2: {n: 2, t: 3}
length: 3

The only explanation I can get is that the map shot syntax without return just work when the function passed doesn't use an index.

What do you think about it?

Mark
  • 5,089
  • 2
  • 20
  • 31

0 Answers0