diff --git a/CHANGELOG.md b/CHANGELOG.md index 777ebd33..12b863a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.13.x + +* Added `Text.fromArray` and `Text.fromVarArray` functions (#674). + ## 0.13.4 * Breaking change (minor): `Float.format(#hex)` is no longer supported. diff --git a/src/Text.mo b/src/Text.mo index 7939b221..8905ebe5 100644 --- a/src/Text.mo +++ b/src/Text.mo @@ -44,6 +44,26 @@ module { /// ``` public let fromChar : (c : Char) -> Text = Prim.charToText; + /// Converts the given `[Char]` to a `Text` value. + /// + /// ```motoko include=import + /// let text = Text.fromArray(['A', 'v', 'o', 'c', 'a', 'd', 'o']); // "Avocado" + /// ``` + /// + /// Runtime: O(a.size()) + /// Space: O(a.size()) + public func fromArray(a : [Char]) : Text = fromIter(a.vals()); + + /// Converts the given `[var Char]` to a `Text` value. + /// + /// ```motoko include=import + /// let text = Text.fromVarArray([var 'E', 'g', 'g', 'p', 'l', 'a', 'n', 't']); // "Eggplant" + /// ``` + /// + /// Runtime: O(a.size()) + /// Space: O(a.size()) + public func fromVarArray(a : [var Char]) : Text = fromIter(a.vals()); + /// Iterates over each `Char` value in the given `Text`. /// /// Equivalent to calling the `t.chars()` method where `t` is a `Text` value. @@ -76,7 +96,7 @@ module { func _ { switch (cs.next()) { case (?c) { c }; - case (null) { Prim.trap("Text.toArray") }; + case null { Prim.trap("Text.toArray") }; }; } ) diff --git a/test/Text.test.mo b/test/Text.test.mo index f98c0bc6..0ad5957e 100644 --- a/test/Text.test.mo +++ b/test/Text.test.mo @@ -1038,6 +1038,16 @@ run( "toArray-example", Array.freeze(Text.toVarArray("Café")), M.equals(T.array(T.charTestable, ['C', 'a', 'f', 'é'])) + ), + test( + "fromArray-example", + Text.fromArray(['A', 'v', 'o', 'c', 'a', 'd', 'o']), + M.equals(T.text "Avocado") + ), + test( + "fromVarArray-example", + Text.fromVarArray([var 'E', 'g', 'g', 'p', 'l', 'a', 'n', 't']), + M.equals(T.text "Eggplant") ) ] )