Skip to content

Commit

Permalink
feat: add Text.from/toList (#676)
Browse files Browse the repository at this point in the history
  • Loading branch information
ggreif authored Dec 4, 2024
1 parent 6d4caef commit bce8702
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
29 changes: 29 additions & 0 deletions src/Text.mo
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import Char "Char";
import Iter "Iter";
import Hash "Hash";
import List "List";
import Stack "Stack";
import Prim "mo:⛔";

Expand Down Expand Up @@ -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<Char>) : 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<Char> {
var acc : List.List<Char> = 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.
Expand Down
18 changes: 18 additions & 0 deletions test/Text.test.mo
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,24 @@ run(
)
);

run(
suite(
"list-conversions",
[
test(
"toList-example",
Text.toList("Café"),
M.equals(T.list<Char>(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",
Expand Down

0 comments on commit bce8702

Please sign in to comment.