So, I'm trying to do something similar to a paginator (list of page numbers) where the current number is in the middle or as close as can be
Every way I solve it is hard and weird, just wondering if there is a nice mathy way to do it :)
given:
a
: current page numberx
: first page numbery
: last page numbern
: number requiredI want to generate a list of numbers where a
is as close to the center as can be, while staying within x
and y
so f(5, 1, 10, 5)
would return [3, 4, 5, 6, 7]
but f(1, 1, 10, 5)
would return [1, 2, 3, 4, 5]
and f(9, 1, 10, 5)
would return [6, 7, 8, 9, 10]
Can anyone think of a nice way of getting that kind of thing?
Implemented in a probably complicated way in ruby, can it be done simpler?
def numbers_around(current:, total:, required: 5)
required_before = (required - 1) / 2
required_after = (required - 1) / 2
before_x = current - required_before
after_x = current + required_after
if before_x < 1
after_x += before_x.abs + 1
before_x = 1
end
if after_x > total
before_x -= (after_x - total)
after_x = total
end
(before_x..after_x)
end
Here's something kind of mathy that returns the first number in the list (JavaScript code):
function f(a,x,y,n){
var m = n >> 1;
return x * (n > y - x) || a - m
+ Math.max(0,m - a + x)
- Math.max(0,m - y + a);
}
Output:
console.log(f(5,1,10,5)); // 3
console.log(f(1,1,10,5)); // 1
console.log(f(9,1,10,5)); // 6
console.log(f(2,1,10,5)); // 1
console.log(f(11,1,10,5)); // 6
console.log(f(7,3,12,10)); // 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With