1
\$\begingroup\$

I've just started with coffeescript, and I saw http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html which has a little programming problem, so I figured I'd do it in coffeescript (which seemed easy enough to do... )

anyways, I ended up with :-

lineEndings = ( s, len ) ->
  words = s.split ' '
  line = ''
  result = ''
  words.map ( word ) ->    
    if line.length == 0
      line = word
    else if line.length + 1 + word.length <= len    
      line = line + ' ' + word
    else     
      result = result + line + '\n'
      line = word  
  result + line

getty = "Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal"  
console.log lineEndings getty, 13

I'm looking for any ways I could make this simpler coffeescript.

( I just used nodejs with coffescript installed to test this )

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

This is how I would write it.

lineEndings = (s, len) ->
  words = s.split ' '
  line = []
  result = []
  for word in words
    if line.length + 1 + word.length <= len
      line = [line..., word]
    else
      result.push line.join ' '
      line = [word]
  lastLine = line.join ' '
  result.push lastLine if lastLine
  result.join "\n"

There's nothing wrong with how you wrote it, though.

\$\endgroup\$
2
\$\begingroup\$
  1. In your case you should use forEach method or for statement instead of map. map has more specific purpose.
  2. You could extract more generic method, though it's not necessary.

.

slice_reduce = (xs, slice_predicate, reduce_functor) ->
  reduction = nil
  slices = []
  if xs.length > 0
    for x in xs
      if slice_predicate(reduction, x)
        slices.push(reduction)
        reduction = x
      else
        reduction = reduce_functor(reduction, x)
    slices.push(reduction)
  slices         

word_wrap = (s, len) ->
  slice_reduce(s.split(/\s+/),
    ((r, w) -> r.length + 1 + w.length <= len),
    ((r, w) -> r + ' ' + w)).
    join('\n')
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.