Skip to content

Instantly share code, notes, and snippets.

@matthijsgroen
Created October 27, 2011 10:28
Show Gist options
  • Save matthijsgroen/1319233 to your computer and use it in GitHub Desktop.
Save matthijsgroen/1319233 to your computer and use it in GitHub Desktop.
Wraps text. using Transformation Priority Premise
def find_positions_for_split(text, width)
if space = text[0..width].rindex(" ")
[space-1, space+1]
else
[width-1, width]
end
end
def wrap(text, width)
return "" unless text
return text if text.length <= width
first, last = find_positions_for_split(text, width)
"#{text[0..first]}\n#{wrap(text[last..-1], width)}"
end
describe "Word wrap" do
# test: nil -> constant
# code: {} -> nil -> contant
it "wraps nil to empty string" do
wrap(nil,3).should eql("")
end
it "wraps empty string to empty string" do
wrap("",3).should eql("")
end
# code : const -> scalar
# code unconditional -> conditional
it "wraps a single word into a single word" do
wrap("word", 5).should eql "word"
end
# code: unconditional -> conditional
# code: nil -> constant
# code: constant -> scalar
it "breaks long words" do
wrap("longword", 4).should eql "long\nword"
# code: statement -> function
wrap("longerword", 6).should eql "longer\nword"
end
# code: statement -> recursion
it "breaks long words multiple times" do
wrap("verylongword", 4).should eql "very\nlong\nword"
end
# code: unconditional -> conditional
# code: nil -> constant
it "splits multiple word on space" do
wrap("word word", 6).should eql "word\nword"
# code: statement -> function
wrap("wrap here", 6).should eql "wrap\nhere"
# code: statement -> recursion
wrap("word word word", 6).should eql "word\nword\nword"
end
# code: statement -> function
it "splits at the end" do
wrap("word word word", 9).should eql "word word\nword"
end
it "splits in the middle" do
wrap("word word word word", 9).should eql "word word\nword word"
wrap("word word word word", 10).should eql "word word\nword word"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment