skip to Main Content

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


  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));
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search