Skip to content

Instantly share code, notes, and snippets.

@matfournier
Last active January 31, 2019 06:17
Show Gist options
  • Save matfournier/a608cb9407def6140f52943854c07b74 to your computer and use it in GitHub Desktop.
Save matfournier/a608cb9407def6140f52943854c07b74 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module Wrap where
import qualified Data.Text as T
import Prelude hiding (Word)
import Data.List
type LinePos = Int
type Word = T.Text
data StringFragment = StringFragment {t :: T.Text, i :: LinePos}
inputText :: T.Text
inputText = "Some text for me"
breakTextAt :: T.Text -> Int -> T.Text
breakTextAt text int = t result
where result = foldl (\acc w -> f acc w) emptyFragment words
words = T.words text
emptyFragment = StringFragment "" 0
f fragment word = concatFragment fragment word int
wordAtBreak :: Int -> Word -> LinePos -> Bool
wordAtBreak breakPos word pos = if endOfWordPos >= breakPos && (endOfWordPos `mod` breakPos) /= 0
then True
else False
where endOfWordPos = pos + T.length word
concatFragment :: StringFragment -> Word -> Int -> StringFragment
concatFragment (StringFragment s pos) word breakPos
| pos == 0 = StringFragment (s <> word) (T.length word)
| otherwise = if breakCondition word pos
then StringFragment lineBrokenWord (T.length word)
else StringFragment normal (pos + T.length word + 1)
where breakCondition = wordAtBreak breakPos
lineBrokenWord = s <> "\n" <> word
normal = s <> " " <> word
class Wrapper {
def wrap(s: String, colNum: Int): String = {
val ss = s.split(" ")
def nextWordIsAtBreak(word: String, curPos: Int): Boolean = {
val posAtEndOfWord = curPos + word.length
if (posAtEndOfWord > colNum && posAtEndOfWord % colNum != 0) true
else false
}
val (wrappedString, _) = ss.foldLeft(("", 0))((acc, elem) => {
val (accumulatedString, pos) = acc
if (pos == 0) {
(accumulatedString ++ elem, elem.length)
} else {
if (nextWordIsAtBreak(elem, pos)) {
(accumulatedString ++ "\n" ++ elem, elem.length)
} else {
(accumulatedString ++ " " ++ elem, pos + elem.length + 1)
}
}
}
)
wrappedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment