Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Text.from/toList #676

Merged
merged 3 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading