var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
list.push(i);
}
Answer from Ben on Stack OverflowCreate a range between two numbers in JavaScript - Stack Overflow
tips - Shortest code to check if a number is in a range in JavaScript - Code Golf Stack Exchange
javascript - How to check if a number is between two values? - Stack Overflow
Is there a shorthand way of checking if a variable is in between two values?
As per Bob's comment it looks like you just need to get a random number between 0 and the array length (less the required span) for your lower limit and then add the required span back to it for the upper limit. e.g.
let myArray = [];
for (let i = 0; i<101; i++){
myArray.push({objectID:i})
}
let requiredSpan = 6;
let lowerBand = Math.floor(Math.random()*(myArray.length-requiredSpan));
let upperBand = lowerBand + requiredSpan-1;
console.log(lowerBand, upperBand);
Just to complete the Mark Taylor's Answer here a more reusable way
let myArray = [];
for (let i = 0; i<101; i++){
myArray.push({objectID:i})
}
const randomMaxMin = max => min => Math.floor(Math.random()*(max-min))
const lowerBand = requiredSpan => length => randomMaxMin(length)(requiredSpan);
const upperBand = requiredSpan => lowerBand => requiredSpan + lowerBand-1;
const getLowerAndUpperBand = requiredSpan => length => {
const lower = lowerBand(requiredSpan)(length);
return {
lower: lower,
upper: upperBand(requiredSpan)(lower)
}
}
console.log(getLowerAndUpperBand(6)(myArray.length))
You can even specialize the generic function by choosing the requiredSpan
const getLowerAndUpperBandSix = getLowerAndUpperBand(6)
console.log(getLowerAndUpperBandSix(myArray.length))
Tests whether windowsize is greater than 500 and lesser than 600 meaning that neither values 500 or 600 itself will result in the condition becoming true.
if (windowsize > 500 && windowsize < 600) {
// ...
}
I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:
Number.prototype.between = function(a, b) {
var min = Math.min(a, b),
max = Math.max(a, b);
return this > min && this < max;
};
var windowSize = 550;
console.log(windowSize.between(500, 600));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
JS Fiddle demo.
Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:
Number.prototype.between = function(a, b, inclusive) {
var min = Math.min(a, b),
max = Math.max(a, b);
return inclusive ? this >= min && this <= max : this > min && this < max;
}
var windowSize = 500;
console.log(windowSize.between(500, 603, true));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
JS Fiddle demo.
References:
Math.max().Math.min().