diff --git a/CHANGELOG.md b/CHANGELOG.md index 12b863a0..7afbbec9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## 0.13.x +* Added `Text.fromList` and `Text.toList` functions (#676). + * Added `Text.fromArray` and `Text.fromVarArray` functions (#674). ## 0.13.4 diff --git a/src/Text.mo b/src/Text.mo index 8905ebe5..e0bd4ae5 100644 --- a/src/Text.mo +++ b/src/Text.mo @@ -23,6 +23,7 @@ import Char "Char"; import Iter "Iter"; import Hash "Hash"; +import List "List"; import Stack "Stack"; import Prim "mo:⛔"; @@ -139,6 +140,34 @@ module { return r }; + /// Create a text from a character list. + /// Example: + /// ```motoko include=initialize + /// fromList(?('H', ?('e', ?('l', ?('l', ?('o', null)))))); + /// // => "Hello" + /// ``` + /// + /// Runtime: O(size cs) + /// Space: O(size cs) + public func fromList(cs : List.List) : Text = fromIter(List.toIter cs); + + /// Create a character list from a text. + /// Example: + /// ```motoko include=initialize + /// toList("Hello"); + /// // => ?('H', ?('e', ?('l', ?('l', ?('o', null))))) + /// ``` + /// + /// Runtime: O(t.size()) + /// Space: O(t.size()) + public func toList(t : Text) : List.List { + var acc : List.List = null; + for (c in t.chars()) { + acc := ?(c, acc) + }; + List.reverse acc + }; + /// Returns the number of characters in the given `Text`. /// /// Equivalent to calling `t.size()` where `t` is a `Text` value. diff --git a/test/Text.test.mo b/test/Text.test.mo index 0ad5957e..61cb5350 100644 --- a/test/Text.test.mo +++ b/test/Text.test.mo @@ -1053,6 +1053,24 @@ run( ) ); +run( + suite( + "list-conversions", + [ + test( + "toList-example", + Text.toList("Café"), + M.equals(T.list(T.charTestable, ?('C', ?('a', ?('f', ?('é', null)))))), + ), + test( + "fromList-example", + Text.fromList(?('H', ?('e', ?('l', ?('l', ?('o', null)))))), + M.equals(T.text "Hello") + ) + ] + ) +); + run( suite( "text-toLowercase",