diff --git a/src/String/Extra.elm b/src/String/Extra.elm index 6f5a9ec..dae8053 100644 --- a/src/String/Extra.elm +++ b/src/String/Extra.elm @@ -2,7 +2,7 @@ module String.Extra exposing ( toSentenceCase, toTitleCase, decapitalize , camelize, classify, underscored, dasherize, humanize , replaceSlice, insertAt, nonEmpty, nonBlank, removeAccents - , break, softBreak + , break, softBreak, words , wrap, wrapWith, softWrap, softWrapWith, quote, surround , isBlank, countOccurrences , clean, unquote, unsurround, unindent, ellipsis, softEllipsis, ellipsisWith, stripTags, pluralize @@ -33,7 +33,7 @@ Functions borrowed from the Rails Inflector class ## Splitting -@docs break, softBreak +@docs break, softBreak, words ## Wrapping @@ -897,3 +897,23 @@ regexEscape = regexFromString : String -> Regex regexFromString = Regex.fromString >> Maybe.withDefault Regex.never + + +{-| Adapt the standard library implementation to behave "better" on blank text. +It follows the definition that the empty string is never a word, +so there are 0 words in blank text. + + words "" == [] + + words " \t\n \r\n\n\u00a0 " == [] + +Aside for blank text (as judged by `isBlank`, `String.Extra.words` behaves like `String.words`. + +-} +words : String -> List String +words text = + if isBlank text then + [] + + else + String.words text diff --git a/tests/WordsTest.elm b/tests/WordsTest.elm new file mode 100644 index 0000000..2e17425 --- /dev/null +++ b/tests/WordsTest.elm @@ -0,0 +1,41 @@ +module WordsTest exposing (allTests) + +import Expect +import Fuzz exposing (Fuzzer, list, string) +import List exposing (foldl) +import String.Extra exposing (isBlank) +import Test exposing (Test, fuzz) + + +fuzzMultilineText : Fuzzer String +fuzzMultilineText = + let + -- Is there a system-independent value for newline? + newlineCharacter = + "\n" + + appendLine text followingLine = + text ++ followingLine ++ newlineCharacter + in + list string + |> Fuzz.map (foldl appendLine "") + + +allTests : Test +allTests = + fuzz fuzzMultilineText "match String.words when not blank; return [] otherwise" <| + \text -> + let + -- I don't know how to write a fuzzer that generates + -- only non-blank collections of lines, so I combined the two tests, + -- which I otherwise dislike doing. + expected = + if isBlank text then + [] + + else + String.words text + in + Expect.equal + expected + (String.Extra.words text)