iteration(2/0)

Simplify loop with iterator swap

When operating on two or more collections you may encounter loops that filter one collection by another. Say we have a collection of dinners and a collection of ingredients. We want to find out, given our ingredients, which dinners are using at least one ingredient. We might write our filter like this: const dinners = this.getDinnerRecipes(); const ingredients = this.getIngredients(); const dinnerIds = ingredients.map(i => i.dinnerId); const dinnerOptions = dinners.filter(dinner => { if (dinnerIds.…

Favor identifier over index

If there are several arrays of data retrieved from different service calls it can be tempting to iterate over them all by index. const columnsFirst = this.dataService.getFirstData(); const columnsSecond = this.dataService.getSecondData(); columnsTotal = []; for (var i = 0; i < columnsFirst.length(); i++) { const total = columnsFirst[i].value + columnsSecond[i].value; columnsTotal.append(total); } return columnsTotal; Iteration by index is prone to many errors, however. The order of each column array must match, their lengths must equal (although this can be overcome with a null check), and it’s not clear to other developers why there’s a hard dependency between these arrays without further investigation.…