Guest User

Untitled

a guest
Mar 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #!/usr/bin/env ruby -w
  2.  
  3. class Paginate
  4. WRAP = 4
  5. TAGS = %w[ div p a ].map { |s| ["<#{s}>", "</#{s}>"] }.to_h
  6. TAGS.merge! TAGS.invert
  7.  
  8. def process input
  9. line = []
  10. result = [line]
  11. stack = []
  12. count = 0
  13.  
  14. input.each do |word|
  15. case word
  16. when /^<\// then # close tag
  17. if TAGS[word] then
  18.  
  19. stack.pop
  20.  
  21. if count % WRAP == 0 && line.last == TAGS[word] then
  22. line.pop
  23. else
  24. line.push word
  25. end
  26. end
  27. when /^</ then # open tag
  28. if TAGS[word] then
  29. stack.push word
  30. line.push word
  31. end
  32. else # word
  33. line.push word
  34.  
  35. count += 1
  36.  
  37. if count % WRAP == 0 then
  38. line.concat stack.reverse.map { |s| TAGS[s] }
  39.  
  40. line = stack.dup
  41. result.push line
  42. end
  43. end
  44. end
  45.  
  46. result.map { |words| words.join " " }
  47. end
  48. end
  49.  
  50. require "minitest/autorun"
  51.  
  52. class TestPaginate < Minitest::Test
  53. def assert_process exp, input
  54. assert_equal exp, Paginate.new.process(input)
  55. end
  56.  
  57. def test_strip_unsupported_tags
  58. assert_process [""], %w[<html>]
  59. end
  60.  
  61. def test_keep_supported_tags
  62. assert_process ["<div>"], %w[<div>]
  63. end
  64.  
  65. def test_enumerate_non_tags
  66. assert_process ["two words"], %w[two words]
  67. end
  68.  
  69. def test_wrap_at_length
  70. assert_process ["one two three four", "five"], %w[one two three four five]
  71. end
  72.  
  73. def test_wrap_at_length_with_tags
  74. expected = [
  75. "<div> <p> here's a short <a> sentence </a> </p> </div>",
  76. "<div> <p> <a> that should </a>",
  77. ]
  78.  
  79. input = [
  80. "<div>", "<p>", "here's", "a", "short", "<a>",
  81. "sentence", "that", "should", "</a>"
  82. ]
  83. assert_process expected, input
  84. end
  85.  
  86. def test_final_goal
  87. expected = [
  88. "<div> <p> here's a short <a> sentence </a> </p> </div>",
  89. "<div> <p> <a> that should </a> be paginated </p> </div>",
  90. "<div> according to the rules </div>",
  91. "<div> above. </div>",
  92. ]
  93.  
  94. input = [
  95. "<html>", "<div>", "<p>", "here's", "a", "short", "<a>",
  96. "sentence", "that", "should", "</a>", "be", "paginated", "</p>",
  97. "<i>", "according", "</i>", "to", "the", "rules", "above.", "</div>",
  98. "</html>"
  99. ]
  100. assert_process expected, input
  101. end
  102. end
Add Comment
Please, Sign In to add comment