Skip to content

Instantly share code, notes, and snippets.

@sshkarupa
Forked from ahmadshah/randomizer.ex
Created August 7, 2022 20:12
Show Gist options
  • Save sshkarupa/0bea936f5c55c1aacfd3b5df3e6a48ac to your computer and use it in GitHub Desktop.
Save sshkarupa/0bea936f5c55c1aacfd3b5df3e6a48ac to your computer and use it in GitHub Desktop.
Random string in elixir
defmodule Randomizer do
@moduledoc """
Random string generator module.
"""
@doc """
Generate random string based on the given legth. It is also possible to generate certain type of randomise string using the options below:
* :all - generate alphanumeric random string
* :alpha - generate nom-numeric random string
* :numeric - generate numeric random string
* :upcase - generate upper case non-numeric random string
* :downcase - generate lower case non-numeric random string
## Example
iex> Iurban.String.randomizer(20) //"Je5QaLj982f0Meb0ZBSK"
"""
def randomizer(length, type \\ :all) do
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
lists =
cond do
type == :alpha -> alphabets <> String.downcase(alphabets)
type == :numeric -> numbers
type == :upcase -> alphabets
type == :downcase -> String.downcase(alphabets)
true -> alphabets <> String.downcase(alphabets) <> numbers
end
|> String.split("", trim: true)
do_randomizer(length, lists)
end
@doc false
defp get_range(length) when length > 1, do: (1..length)
defp get_range(length), do: [1]
@doc false
defp do_randomizer(length, lists) do
get_range(length)
|> Enum.reduce([], fn(_, acc) -> [Enum.random(lists) | acc] end)
|> Enum.join("")
end
end
defmodule RandomizerTest do
use ExUnit.Case
alias Randomizer
test "generate random string" do
random = Randomizer.randomizer(100)
assert 100 = String.length(random)
assert String.match?(random, ~r/[A-Za-z0-9]/)
end
test "generate random numbers" do
random = Randomizer.randomizer(100, :numeric)
assert 100 = String.length(random)
refute String.match?(random, ~r/[A-Za-z]/)
end
test "generate random upper case" do
random = Randomizer.randomizer(100, :upcase)
assert 100 = String.length(random)
refute String.match?(random, ~r/[a-z0-9]/)
end
test "generate random lower case" do
random = Randomizer.randomizer(100, :downcase)
assert 100 = String.length(random)
refute String.match?(random, ~r/[A-Z0-9]/)
end
test "generate random alphabets only" do
random = Randomizer.randomizer(100, :alpha)
assert 100 = String.length(random)
refute String.match?(random, ~r/[0-9]/)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment