Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby -w
- class Paginate
- WRAP = 4
- TAGS = %w[ div p a ].map { |s| ["<#{s}>", "</#{s}>"] }.to_h
- TAGS.merge! TAGS.invert
- def process input
- line = []
- result = [line]
- stack = []
- count = 0
- input.each do |word|
- case word
- when /^<\// then # close tag
- if TAGS[word] then
- stack.pop
- if count % WRAP == 0 && line.last == TAGS[word] then
- line.pop
- else
- line.push word
- end
- end
- when /^</ then # open tag
- if TAGS[word] then
- stack.push word
- line.push word
- end
- else # word
- line.push word
- count += 1
- if count % WRAP == 0 then
- line.concat stack.reverse.map { |s| TAGS[s] }
- line = stack.dup
- result.push line
- end
- end
- end
- result.map { |words| words.join " " }
- end
- end
- require "minitest/autorun"
- class TestPaginate < Minitest::Test
- def assert_process exp, input
- assert_equal exp, Paginate.new.process(input)
- end
- def test_strip_unsupported_tags
- assert_process [""], %w[<html>]
- end
- def test_keep_supported_tags
- assert_process ["<div>"], %w[<div>]
- end
- def test_enumerate_non_tags
- assert_process ["two words"], %w[two words]
- end
- def test_wrap_at_length
- assert_process ["one two three four", "five"], %w[one two three four five]
- end
- def test_wrap_at_length_with_tags
- expected = [
- "<div> <p> here's a short <a> sentence </a> </p> </div>",
- "<div> <p> <a> that should </a>",
- ]
- input = [
- "<div>", "<p>", "here's", "a", "short", "<a>",
- "sentence", "that", "should", "</a>"
- ]
- assert_process expected, input
- end
- def test_final_goal
- expected = [
- "<div> <p> here's a short <a> sentence </a> </p> </div>",
- "<div> <p> <a> that should </a> be paginated </p> </div>",
- "<div> according to the rules </div>",
- "<div> above. </div>",
- ]
- input = [
- "<html>", "<div>", "<p>", "here's", "a", "short", "<a>",
- "sentence", "that", "should", "</a>", "be", "paginated", "</p>",
- "<i>", "according", "</i>", "to", "the", "rules", "above.", "</div>",
- "</html>"
- ]
- assert_process expected, input
- end
- end
Add Comment
Please, Sign In to add comment