There can be any specified number, then I want to write a function to return the best upper limit number to calculate the interval.
To divide the number into 5 intervals, the best numbers are
- if less than or equal 5 = divide into 1, 2, 3, 4, 5
- if 10 => divide into 2, 4, 6, 8, 10
- if 25 => divide into 5, 10, 15, 20, 25
- if 50 => divide into 10, 20, 30, 40, 50
- if 100 => divide into 20, 40, 60, 80, 100
- if 125 => divide into 25, 50, 75, 100, 125
- If 500 => divide into 100, 200, 300, 400, 500
But the input number, cannot be that 5, 10, 25, 50, 100, 125, 500, ...
So I would like to write a function that can return the best bold number, but i am stuck now. I want to calculate on the fly. No predefined values as I don't know what would be the input number. For less than or equal to 10, i can add additional to handle, but greater than 10, I want to get through by some formula calculation.
input | output |
---|---|
8 | 10 |
13 | 25 |
110 | 125 |
456 | 500 |
1601 | 2000 |
53194 | 60000 |
Is there any formula to calculate so that I can write the function that takes the above input and return the output? Thanks a lot.
The reason not to split 110 into 22, 44, 66, 88, 110, these numbers are not suitable to appear in the chart axis except 2, 4, 6, 8 , 10.
CodePudding user response:
You can create an array of limit values and use find
to to get the first number when the delta becomes positive
const limits = [10, 25, 125, 500, 2000]
const findLimit = (limits, n) => limits .find(a => a - n >= 0)
const inputs = [8, 13, 110, 456, 1601]
inputs.forEach(n =>
console.log(n, findLimit(limits, n))
)
CodePudding user response:
I suggest defining your interval in some way like this:
For a positive input number n
find the minimum interval i
such that i * 5 >= n
and i
is one of the following forms: 10^k, 2 * 10^k, 5 * 10^k, 25 * 10^k
where k
is a non-negative integer.
function interval(n, steps = 5) {
// Find the minimum x such that x = a*b^k >= n / steps, where k is an integer
const solve = (a, b) => a * b ** Math.ceil(Math.log((n / steps) / a) / Math.log(b));
// Return the lowest of the possible solutions
return Math.min(
solve(1, 10),
solve(2, 10),
solve(5, 10),
solve(25, 10)
); // (alternatively Math.min(...[1,2,5,25].map(a => solve(a, 10)))
}
const inputs = [5, 8, 13, 110, 456, 1601, 53194];
console.log("input\tint\tlimit");
for (const n of inputs) {
console.log(n, '\t', interval(n), '\t', 5 * interval(n));
}
This does not match your suggested output in all cases, but does provide sensible and consistent values. You could adjust the forms that are allowed if you want to tweak this.