11defmodule RandomString do
2+ @ moduledoc """
3+ An utility to generate random strings of desired character sets.
4+ """
5+
26 @ simple_classes % {
37 # {base, number_of_chars}
48 numeric: { ?0 , 10 } ,
@@ -9,15 +13,25 @@ defmodule RandomString do
913
1014 @ misleading_chars '01258' ++ 'ijlouv' ++ 'BIOSUVZ'
1115
16+ @ doc """
17+ Take `n` characters from `:alphanumeric` class characters.
18+ """
1219 # public APIs
1320 def take ( n ) when is_integer ( n ) do
1421 take ( n , :alphanumeric )
1522 end
1623
24+ @ doc """
25+ Take `n` characters from a specified character class.
26+ Available character classes are: `:alphabetical`, `:alphanumeric`, `:numeric`, `:lowercase`, `:uppercase`, `printable_chars`.
27+ """
1728 def take ( n , character_class ) when is_integer ( n ) do
1829 stream ( character_class ) |> Enum . take ( n ) |> List . to_string
1930 end
2031
32+ @ doc """
33+ Take `n` characters from alphanumeric characters, excluding "misleading characters" (characters that look similar to another character: `01258ijlouvBIOSUVZ`).
34+ """
2135 def take_without_misleading_characters ( n ) when is_integer ( n ) do
2236 stream_without_misleading_characters ( ) |> Enum . take ( n ) |> List . to_string
2337 end
@@ -31,6 +45,9 @@ defmodule RandomString do
3145
3246
3347 # definition of streams
48+ @ doc """
49+ Returns a [Stream](https://hexdocs.pm/elixir/Stream.html) of characters with a specified character class.
50+ """
3451 def stream ( character_class ) when character_class in [ :numeric , :uppercase , :lowercase , :printable_chars ] do
3552 { base , number_of_chars } = @ simple_classes [ character_class ]
3653 # :rand.uniform returns 1 <= X <= N
@@ -68,6 +85,9 @@ defmodule RandomString do
6885 stream ( character_class ) |> Stream . reject ( fn x -> Enum . member? ( @ misleading_chars , x ) end )
6986 end
7087
88+ @ doc """
89+ Returns a [Stream](https://hexdocs.pm/elixir/Stream.html) of characters that does not include characters specified in `character_list`.
90+ """
7191 def stream_without_characters ( character_list , character_class \\ :alphanumeric ) when is_list ( character_list ) do
7292 stream ( character_class ) |> Stream . reject ( fn x -> Enum . member? ( character_list , x ) end )
7393 end
0 commit comments