diff --git a/src/String/Extra.elm b/src/String/Extra.elm index 67502b6..ebf438e 100644 --- a/src/String/Extra.elm +++ b/src/String/Extra.elm @@ -3,6 +3,7 @@ module String.Extra exposing , camelize, classify, underscored, dasherize, humanize , replaceSlice, insertAt, nonEmpty, nonBlank, removeAccents , break, softBreak + , joinMap , wrap, wrapWith, softWrap, softWrapWith, quote, surround , isBlank, countOccurrences , clean, unquote, unsurround, unindent, ellipsis, softEllipsis, ellipsisWith, stripTags, pluralize @@ -36,6 +37,11 @@ Functions borrowed from the Rails Inflector class @docs break, softBreak +## Joining + +@docs joinMap + + ## Wrapping @docs wrap, wrapWith, softWrap, softWrapWith, quote, surround @@ -205,6 +211,26 @@ softBreakRegexp width = regexFromString <| ".{1," ++ String.fromInt width ++ "}(\\s+|$)|\\S+?(\\s+|$)" +{-| A more performant and easier way of writing + + list + |> List.map f + |> String.join sep + +-} +joinMap : (a -> String) -> String -> List a -> String +joinMap f sep list = + case list of + [ only ] -> + f only + + first :: rest -> + f first ++ sep ++ joinMap f sep rest + + [] -> + "" + + {-| Trim the whitespace of both sides of the string and compress repeated whitespace internally to a single whitespace char. diff --git a/tests/Tests.elm b/tests/Tests.elm index 98fd6c1..fd13ae8 100644 --- a/tests/Tests.elm +++ b/tests/Tests.elm @@ -1,4 +1,23 @@ -module Tests exposing (breakTest, cleanTest, countOccurrencesTest, decapitalizeTest, ellipsisTest, insertAtProducer, insertAtTest, isBlankTest, nonBlankTest, pluralizeTest, softBreakTest, surroundTest, tail, toSentenceCaseTest, toTitleCaseTest, unquoteTest, wrapTest) +module Tests exposing + ( breakTest + , cleanTest + , countOccurrencesTest + , decapitalizeTest + , ellipsisTest + , insertAtProducer + , insertAtTest + , isBlankTest + , joinMapTest + , nonBlankTest + , pluralizeTest + , softBreakTest + , surroundTest + , tail + , toSentenceCaseTest + , toTitleCaseTest + , unquoteTest + , wrapTest + ) import Expect import Fuzz exposing (..) @@ -168,6 +187,20 @@ softBreakTest = ] +joinMapTest : Test +joinMapTest = + describe "joinMap" + [ fuzz2 string (list int) "Should yield the same result as List.map combined with String.join" <| + \sep list -> + Expect.equal + (list + |> List.map String.fromInt + |> String.join sep + ) + (joinMap String.fromInt sep list) + ] + + cleanTest : Test cleanTest = describe "clean"