Skip to content

Instantly share code, notes, and snippets.

@ignasi35
Created May 18, 2013 16:57
Show Gist options
  • Save ignasi35/5605115 to your computer and use it in GitHub Desktop.
Save ignasi35/5605115 to your computer and use it in GitHub Desktop.
Scala solution to the Word Wrap Kata performed during 2013-05-18 at @softonic 's #katayuno
object WordWrap {
/**
* Returns the <code>input</code> text split into lines of length
* smaller or equal to <code>maxLength</code>. The newline
* character is not consistent with the platform, it's always a
* CR character. This input processing also replaces
* consecutive blank spaces with a single blank space.
*
* @param input the text we want to process.
* @param the maximum length of a line
*/
def wrap(input : String, maxLength : Int) = {
input.split (" ").foldLeft ("")(
(acc, in) =>
if (in equals "") acc else if ((acc.length - acc.lastIndexOf('\n') + in.length()) < maxLength) { acc + " " + in }
else { acc + '\n' + in }).trim
}
}
@ignasi35
Copy link
Author

  def wrap(input : String, maxLength : Int) = {
    input.split (" ").foldLeft (("", 0))(
      (acc, in) =>
        if (in equals "") acc else if ((acc._2 + in.length()) < maxLength) { (acc._1 + " " + in, acc._2 + in.length()) }
        else { (acc._1 + '\n' + in, in.length()) })._1.trim
  }

Yes it can be done. :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment