Skip to content

Commit

Permalink
feat: add Text.from/toList
Browse files Browse the repository at this point in the history
  • Loading branch information
ggreif committed Dec 4, 2024
1 parent 6d4caef commit bc0fdbb
Showing 1 changed file with 29 additions and 0 deletions.
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

0 comments on commit bc0fdbb

Please sign in to comment.