The following typescript function seriesIncrementedBy5
returns an array with numbers starting from 5 to upperLimit
with an increment of 5.
Is there a way to replace this 5 lines of code with any recent typescript ES6 advanced function which will take less than 5 lines.
private seriesIncrementedBy5(upperLimit: number): number[] {
const series = [];
for (let s = 5; s <= upperLimit + 5; s += 5) {
series.push(s);
}
return series;
}
3
Answers
You can create an array of the correct size and then
map
over it.You can use the
Array.from
method.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
You can use Array.from, which can accept an object with the
length: number
property and a second argument populating function:To calculate the length, we divide the
upperLimit
by5
and floor it to get an integer; it is crucial to add+ 1
to include theupperLimit
in the array. To populate, we will use the element’s index; since we are starting from5
, not0
, we will add+ 1
to the index and multiply it by5
.playground