We wish to have a function where we can pass in any number of arguments and add them together. So for example:
sum(1,2)
or
sum(1,2,3)
Also we want another function where we can subtract
the first argument from the sum
of the rest. Like this:
addThenSubtract(1,2,3) // Result would be 4
addThenSubtract(1,2,3,4) // Result would be 8
The SPREAD operator is also expressed as ...
. We will see this used when we implement addThenSubtract
.
Approach
Sum
We implement sum
like this.
function sum(...arr: number[]): number {
let sum = 0;
arr.forEach((v) => {
sum += v;
});
return sum;
}
The REST …
operator collects all the arguments into an an array arr for us, and we then calculate the sum.
addThenSubtract
Here we can subtract the first argument from the sum of the rest.
/**
* @param subtract Subract this number from the numbers added
* @param add Add tese numbers together
*/
function addThenSubtract(subtract: number, ...add: number[]) {
console.log(`subtract ${subtract}`);
console.log(`add ${add}`);
const total = sum(...add);
return total - subtract;
}
Note that when we call sum
we use an operator that looks like the REST operator ...
. In this context it’s a SPREAD operator. It takes the values in the add
array and spreads them out. So if we pass in [1,2,3]
it will become 1,2,3
.