Search code examples
javascriptfunctional-programmingunderscore.jscode-readability

How to change only one specific object in array of objects in functional style?


Let's assume we want to create some very readable code which does the next:

  1. iterates through all elements of list
  2. changes all of them equally except only one specific element (even though more than one element can satisfy search criteria)
  3. return this list with changed elements
  4. uses _.underscore power

For example, i want to add property isChosen with true value only to the first element which has hasRoom property, other element should get false value for this new property hasRoom

Here is code created using _.underscore lib:

  var i = 0
  var changedList = []
  _.each(list, function(el) {
    if (el.hasRoom && i === 0) {
      _.extend(el, { isChosen: true })
      i++
    } else {
      _.extend(el, { isChosen: false })
    }
    changedList.push(el)
  })

This code works, but I think there can be better way of making same, maybe with _.chain()?

So, as input we can have

[
    {hasRoom: false}, 
    {hasRoom: true}, 
    {hasRoom: true}
]

And as result we should get

[
    {hasRoom: false, isChosen: false}, 
    {hasRoom: true,  isChosen: true}, 
    {hasRoom: true,  isChosen: false}
]

Solution

  • This solution modifies the function that sets the isChosen:

    function notChosen(place){
      return false;
    }
    
    function chosen(place){
      if( !place.hasRoom ) return notChosen(place);
      setChosen = notChosen;
      return true;
    }
    
    var setChosen = chosen;
    
    _.each(places, function(place){
        place.isChosen = setChosen(place);
    });
    

    The if statement will only be executed until the first place with a room is found.