From bc0fdbbd44b5101ad84912efe873942268e1cee9 Mon Sep 17 00:00:00 2001 From: Gabor Greif Date: Wed, 4 Dec 2024 16:36:44 +0100 Subject: [PATCH 1/3] feat: add `Text.from/toList` --- src/Text.mo | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) 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. From d175e97015f396a6af5f27feabf5c06d0611c15e Mon Sep 17 00:00:00 2001 From: Gabor Greif Date: Wed, 4 Dec 2024 16:48:33 +0100 Subject: [PATCH 2/3] tests --- test/Text.test.mo | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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", From 209f1786ddebf31fdb51b42b7986a7685d08cacd Mon Sep 17 00:00:00 2001 From: Gabor Greif Date: Wed, 4 Dec 2024 17:13:16 +0100 Subject: [PATCH 3/3] add `CHANGELOG.md` items --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) 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