How to split a number in ranges of a given range

Viewed 517

I'm trying to split a number say TotalRecords in a given range intervals of say 'X' and round the last item to the nearest range 'X'

Example:

'X' Range = 50
TotalRecords = 120.

What i'm expecting is 50,100,150 (120 is rounded to the last range).

3 Answers

This is rough but maybe is something like what you are are after.

function listRange(x,y) { 
   let a = new Array();
   let start = x;
   do {
     a.push(start);
     start += x;
   } while (start < y)
  if (start != y) a.push(y);
  return a;

} 

var nums = listRange(50,120); 
for (var i in nums) { 
   console.log(nums[i]); 
}

I have come up with the following solution.

function spiltNumbers( range:number, totalRecords:number ) : Array<number> {
    const range = range;
    const totalRecords = totalRecords;
    let times = totalRecords % range;
    let limit = 0;
    let array = []; // array to store ranges;

    const remainder = totalRecords - range * times;
    times = remainder ? times : times++;

    while( limit < times ) {
        array.push( range * ( limit + 1 ) );
        limit++;
    }
    return array;
}

I hope this will help! :)

I'm not sure, if I have understand you correctly. But try something like that:

splitNumbers(range: number, totalRecords: number): number[] {
   const count = Math.ceil(totalRecords / range);
   const arr: number[] = [];

   for (let i = 1, i <= count, i++) {
      arr.push(range * i);
   }

   return arr;
}

To test your function:

console.log(splitNumbers(50, 120));
// expected output: [ 50, 100, 150] 
Related