I want to create an array of 9 values as result, where i have written a function which takes the min and max value
function generateSequence(min, max, numElements = 9) {
// Step 1: Calculate the raw step size
let step = (max - min) / (numElements - 3); // One value below min, and one above max
// Step 2: Dynamically determine the rounding factor based on the step size
const orderOfMagnitude = Math.pow(10, Math.floor(Math.log10(step))); // Find the magnitude (e.g., 10, 100, 1000)
// Step 3: Round the step to the nearest multiple of the order of magnitude
const roundedStep = Math.round(step / orderOfMagnitude) * orderOfMagnitude;
// Step 4: Start from a value a bit lower than the min, ensuring we have one value below min
const startValue = Math.floor(min / roundedStep) * roundedStep - roundedStep;
// Step 5: End at a value a bit higher than the max, ensuring we have one value above max
const endValue = Math.ceil(max / roundedStep) * roundedStep + roundedStep;
// Step 6: Generate the sequence with the dynamically adjusted start and end
const sequence = Array.from({ length: numElements }, (_, i) => startValue + i * roundedStep);
return sequence;
}
[[100,200],
[23166,67123],
[25000,76500]].forEach(([min,max]) => console.log(generateSequence(min, max)))
I want to get only one value above the max value and one value less than the min value, if you see the result it’s giving me 220 & 240. Ideally with 220 the array should end, but then I need 9 integers which will get reduced to 8, so I want to shift my first integer to some more lower value and based on that sequence should get generated.
I need some rounded values if you check this kind of cases
const min = 23166;
const max = 67123;
I should get a clean integer value like 16000, 23000,
2
Answers
Details are commented in example.
Your code logic is far from generating an array that meets the conditions specified in your question. The code below will generate the expected array.