Use less-than instead of not-equal-to e.g. while (array[array.length - 1] < 100)
, because you will not get EXACTLY 100, due to the nature of floating-point arithmetic.
See the output from the program below.
console.log(generateSequence(0, 100, 0.1));
function generateSequence(start, end, step) {
let result = [];
do {
const prev = result[result.length - 1] ? result[result.length - 1] : 0;
result.push(prev + step);
} while (result[result.length - 1] < 100);
return result;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Alternatively
You can increase the magnitude of the number, floor it, then divide it.
As you can see it works for multiple precisions.
console.log(generateSequence(0, 100, 1).join(', '));
console.log(generateSequence(0, 100, 10).join(', '));
console.log(generateSequence(0, 100, 0.1).join(', '));
console.log(generateSequence(0, 100, 0.025).join(', '));
function generateSequence(start, end, step) {
let result = [],
trueEnd = end / step,
precision = step < 1 ? 1 / step : 1,
p2 = Math.pow(precision, 2);
for (let i = 0; i < trueEnd; i++) {
result.push(Math.floor(i * precision) / p2);
}
return result;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }