Created
June 8, 2012 17:40
-
-
Save cromwellryan/2897150 to your computer and use it in GitHub Desktop.
Word wrap Kata in coffeescript
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
wrap = (sent, col) -> | |
result = '' | |
if sent.length <= col | |
result = sent | |
else | |
space = sent.substring(0,col).lastIndexOf(' ') | |
wrapline = (sent, stop, skip) -> | |
sent.substring(0,stop) + '\n' + wrap(sent.substring(stop+skip),col) | |
if space != -1 | |
result = wrapline sent, space, 1 | |
else if sent[col] == ' ' | |
result = wrapline sent, col, 1 | |
else | |
result = wrapline sent, col, 0 | |
result |
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
describe 'wrapper', -> | |
it 'doesn`t wrap short words', -> | |
expect( wrap('foo',88888) ).toBe 'foo' | |
expect( wrap('bar',88888) ).toBe 'bar' | |
it 'hard splits a single long word', -> | |
expect( wrap('foofoo', 3) ).toBe 'foo\nfoo' | |
expect( wrap('foobar', 3) ).toBe 'foo\nbar' | |
expect( wrap('foobar', 4) ).toBe 'foob\nar' | |
it 'wraps more than once', -> | |
expect( wrap('foobarwoo', 3) ).toBe 'foo\nbar\nwoo' | |
it 'prefers spaces', -> | |
expect( wrap('foo bar', 5) ).toBe 'foo\nbar' | |
expect( wrap('big bad wolf', 5) ).toBe 'big\nbad\nwolf' | |
expect( wrap('foo bar bad', 9) ).toBe 'foo bar\nbad' | |
expect( wrap('foo bar', 3) ).toBe 'foo\nbar' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment