Created
June 5, 2015 14:56
-
-
Save lnaia/58434f93d239d7c53000 to your computer and use it in GitHub Desktop.
Sapo exercice in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "awesome_print" | |
def pagination(current_page, total_pages, boundaries, around) | |
elements = [] | |
# add boundaries elements | |
(1..boundaries).to_a.each { |val| | |
elements.push(val) | |
elements.push(total_pages-val+1) | |
} | |
# add around elements top limit | |
# exclude current page by adding +1 to starting range | |
(current_page+1..current_page+around).to_a.each { |val| | |
elements.push(val) unless elements.include?(val) | |
} | |
# add around elements bottom limit | |
# include current page by the inverse reason of before | |
(current_page-around..current_page).to_a.each { |val| | |
elements.push(val) unless elements.include?(val) | |
} | |
elements.sort! | |
elements.uniq! | |
elements.select!{ |val| val if val > 0 and val <= total_pages} # filter out elements that we don't need | |
elements_clone = elements.clone # we need to iterate trough a copy and change the original | |
shifts_needed = 0 # are to compensate the index of the original array, that is changed by inserting the ... | |
old_value = nil # used to detect the gaps between current and past values | |
elements_clone.each_with_index { |val, index| | |
if old_value.nil? | |
old_value = val | |
next | |
end | |
#puts "val: #{val}, old: #{old_value}, index: #{index}, diff: #{val-old_value}" #debug output | |
if (val-old_value) > 1 | |
#puts "gap found at: #{index}" #debug output | |
elements.insert((index+shifts_needed), '...') | |
shifts_needed += 1 | |
end | |
old_value = val | |
} | |
puts elements.to_s | |
elements | |
end | |
pagination(4, 5, 1, 0) # [1, "...", 4, 5] | |
pagination(4, 10, 2, 2) # [1, 2, 3, 4, 5, 6, "...", 9, 10] | |
pagination(6, 30, 2, 2) #[1, 2, "...", 4, 5, 6, 7, 8, "...", 29, 30] | |
pagination(1, 10, 2, 2) # [1, 2, 3, "...", 9, 10] | |
pagination(6, 30, 2, 2) # [1, 2, 3, "...", 9, 10] | |
pagination(10, 10, 10, 10) # [1, "...", 4, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment