From bc0fdbbd44b5101ad84912efe873942268e1cee9 Mon Sep 17 00:00:00 2001 From: Gabor Greif Date: Wed, 4 Dec 2024 16:36:44 +0100 Subject: [PATCH] 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.