Skip to content

Commit

Permalink
feat: add Text.from(Var)Array (#674)
Browse files Browse the repository at this point in the history
Using `fromIter` is probably less-than-optimal performance-wise, but we
can add a compiler primitive if it proves to become a bottleneck. For
now it fills a hole that I perceived in the Motoko AI hackathon.

Adds test for both `Text.fromArray` and `fromVarArray`.
  • Loading branch information
ggreif authored Dec 4, 2024
1 parent 12aeff2 commit 6d4caef
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
22 changes: 21 additions & 1 deletion src/Text.mo
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -76,7 +96,7 @@ module {
func _ {
switch (cs.next()) {
case (?c) { c };
case (null) { Prim.trap("Text.toArray") };
case null { Prim.trap("Text.toArray") };
};
}
)
Expand Down
10 changes: 10 additions & 0 deletions test/Text.test.mo
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,16 @@ run(
"toArray-example",
Array.freeze(Text.toVarArray("Café")),
M.equals(T.array<Char>(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")
)
]
)
Expand Down

0 comments on commit 6d4caef

Please sign in to comment.