Skip to content

Instantly share code, notes, and snippets.

@cromwellryan
Created June 8, 2012 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cromwellryan/2897150 to your computer and use it in GitHub Desktop.
Save cromwellryan/2897150 to your computer and use it in GitHub Desktop.
Word wrap Kata in coffeescript
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
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