Home > Mobile >  Javascript: return all rangs between two numbers based on a number
Javascript: return all rangs between two numbers based on a number

Time:02-08

I have a case where I need to split a range of numbers [1, 60] into ranges that has 11 in each.

I want to push each range into JSON Array, so the expected result would be:

[
{'first: 1, 'last': 11},  // count = 11
{'first: 12, 'last': 22}, // count = 11
{'first: 23, 'last': 33}, // count = 11
{'first: 34, 'last': 44}, // count = 11
{'first: 45, 'last': 55}, // count = 11
{'first: 56, 'last': 60}  // the rest, count = 5
]

My code so far:

var count = 11, first = 1, last = 60;
var all = [];
var starter = first;
for(i = first; i <= last; i  ){
if(i % count == 0){
all.push({'first': (i - count   (all.length == 0 ? 1 : 0)), 'last': (i-1)});
 }
}
console.log(all);

My code return only 5 ranges not 6 as expected and this code not work for all cases like [1, 10] and it return wrong result in many other cases.

CodePudding user response:

You could take a multiple of count and get the ranges.

function getRanges(first, to, count) {
    const result = [];
    while (first < to) {
        let last = Math.min(to, (Math.floor(first / count)   1) * count);
        if (last   1 === to) last = to;
        result.push({ first, last });
        first = last   1;
    }
    return result;
}

console.log(getRanges(1, 60, 11));
console.log(getRanges(1, 11, 5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

var count = 11, first = 1, last = 60;
var all = [];
for(i = first; i <= last; i  = count){
    var l = i   count - 1;
    all.push({'first': i, 'last': l > last ? last : l});
}
console.log(all);
  •  Tags:  
  • Related