Simple examples

This section presents various simple examples to demonstrate the functional way of thinking. The demonstration consists of toy examples and do not showcase all that functional programming has to offer. Don't worry if you find the declarative JavaScript code incomprehensible at the moment. The remainder of the book is meant to help you learn the functional way of programming.

Sum it up

You have an array of all integers between 0 and 9, inclusive. How would you add together all numbers in the array? An imperative program to achieve the desired result might be as follows.

const num = [...Array(10).keys()]; let total = 0; for (let i = 0; i < num.length; i++) { total += num[i]; } console.log(total);

The above program describes step-by-step how to obtain the sum of integers in an array. The instructions can be summarized as follows.

initially the total is 0
for each element in the array
    add the element to the running total

Contrast the imperative program above with the functional version below.

const num = [...Array(10).keys()]; const add = (acc, curr) => acc + curr; const total = num.reduce(add, 0); console.log(total);

The functional program says this.

add is the function to obtain cumulative sum
reduce the array elements to a value, using the function add

We describe the result we want. The looping is delegated to the array method reduce() and we tell it to use the function add() to obtain the cumulative sum.

Sum even integers

Here's a variation on the summing problem from the section Sum it up. Add together all even numbers in an array of random integers. A step-by-step description might be something like:

let total = 0; for (let i = 0; i < 10; i++) { const n = Math.floor(100 * Math.random()); if (n % 2 === 0) { total += n; } } console.log(total);

A declarative version might be something along the line of:

const random = () => Math.floor(100 * Math.random()); const randint = [...Array(10).keys()].map(() => random()); const isEven = (x) => x % 2 === 0; const add = (acc, curr) => acc + curr; const total = randint.filter(isEven).reduce(add, 0); console.log(total);

results matching ""

    No results matching ""