0

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;
}
wonderflame
  • 6,759
  • 1
  • 1
  • 17
wonderful world
  • 10,969
  • 20
  • 97
  • 194
  • 1
    Does [this approach](https://tsplay.dev/Nn8LVW) work for you? If yes, I'll write an answer explaining; If not, what am I missing? – wonderflame May 22 '23 at 15:12
  • 1
    Array.from().... https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n – epascarello May 22 '23 at 15:14
  • @wonderflame Yes. That code works. You can move your comment to answer section, and I will choose as the correct answer. – wonderful world May 22 '23 at 15:20

3 Answers3

2

You can use Array.from, which can accept an object with the length: number property and a second argument populating function:

const seriesIncrementedBy5 = (upperLimit: number): number[] =>
  Array.from({ length: Math.floor(upperLimit / 5) + 1 }, (_, i) => (i + 1) * 5);

To calculate the length, we divide the upperLimit by 5 and floor it to get an integer; it is crucial to add + 1 to include the upperLimit in the array. To populate, we will use the element's index; since we are starting from 5, not 0, we will add + 1 to the index and multiply it by 5.

playground

wonderflame
  • 6,759
  • 1
  • 1
  • 17
1

You can create an array of the correct size and then map over it.

const seriesIncrementedBy5 = upperLimit => [...Array((upperLimit/5|0)+1)]
        .map((_, i) => 5 * (i + 1));
console.log(seriesIncrementedBy5(10));
console.log(seriesIncrementedBy5(9));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use the Array.from method.

private seriesIncrementedBy5(upperLimit: number): number[] {
  return Array.from({ length: Math.floor(upperLimit / 5) }, (_, i) => (i + 1) * 5);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from