Try to Code Without Loops

Đọc và xem cốt đê =]], Cấm phân tâm hình gái.

Challenge #1: Compute the sum of a list of numbers

Let’s say we have an array of numbers and we need to compute the sum of these numbers.

Here is an example to test with:

Here is a solution using a loop:

Note how we had to mutate the  sum variable to accomplish the solution.

Here is a solution using the excellent reduce function:

Nothing was mutated with the reduce-based solution. Instead, we made a bunch of calls to the callback function and the state was carried along between these calls until we arrived at our final  sum state.

Here is the same challenge above solved with recursion:

The  sum function calls itself and on every turn it uses the rest operator to reduce the array it is summing. It stops when that reduced array is empty. While you might think this is a clever solution, I do not think it is as readable as using a simple  reduce call.

Challenge #2: Make a sentence from mixed content

Let’s say we have an array of strings and other types and we need to join all the strings and ignore the other types.

Here is an example to test with:

The desired output is “Hello!”.

You can simply use the  typeof operator to check if a value is of type  string.

Here is a solution using a simple loop:

Here is a solution using the filter method combined with the join method:

Note how using the  filter method also allowed us to get rid of an if-statement! The conditional processing is now abstracted away inside the filter call.

Challenge #3: Convert values to records

Let’s say we have an array of book titles and we need to convert every title into an object and give that object a unique ID.

Here is an example to test with:

Here is a solution using a simple loop:

Here is a solution using a simple map call:

The  map/ filter/ reduce methods are my favorite methods on arrays.

Credit to Steven Luscher

Please follow and like us:

Leave a reply

Your email address will not be published.