Let's assume we want to create some very readable code which does the next:
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}
]
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.