Your initial attempt wouldn't be considered functional because it alters the original input.
This presents a problem as, in addition to managing program execution flow, you must also consider data manipulation. For instance:
const last = arr => arr.pop();
const sum = ([a, b]) => a + b;
const x = [4, 2];
const y = [4, 2];
// Expected Behavior
sum(x); //=> 6
last(x); //=> 2
// Issue!
last(y); //=> 2
sum(y); //=> NaN
The problem lies in the fact that Array#pop
modifies the array. It becomes apparent that the order of execution now impacts the outcome for the same inputs. This unnecessary complexity leads to program instability and introduces bugs that can be challenging to identify and resolve.
If your goal is to multiply all elements in an array by 5
, the most straightforward and functional approach would be using xs.map(x => x * 5)
.
In functional programming, there's a concept called unfold
which generates a list by repeatedly applying a function on a value until a condition is met:
unfold(mult5, 1); // starting with 1 and multiplying by 5 up to 10.
//=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
However, when the boundaries are known beforehand, such as needing the first n multiples of 5
, we can optimize the process:
Let's set aside 10 slots for our multiples of five:
const xs = Array(10);
//=> An array of 10 empty values
Note: Mapping over this kind of array won't work!
const ys = xs.map(x => x * 5);
//=> Still an array of 10 empty values!
To address this, use Array.from
:
const ys = Array.from(xs, (_, i) => (i + 1) * 5);
//=> [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]