A Quick Utility Module

olddutchcap

Onorio Catenacci

Posted on April 30, 2024

A Quick Utility Module

I was working on some code with a friend of mine and we came up with what seems a relatively clever way to do a couple of validations. I'm putting this post here to share this in case it benefits anyone else:

defmodule Validations do
  @moduledoc """
  This module contains a few validation predicate functions.
  """

  @doc """
  Checks if a string contains only specified characters.  The specified characters are passed in a list. The list can be one or more characters. You could pass an empty list if you wished but that would always return false.

  ## Examples

      iex> Validations.string_contains_only_specified_chars?("abc", ["a", "b", "c"])
      true

      iex> Validations.string_contains_only_specified_chars?("abr", ["a", "b", "c"])
      false
  """

  @spec string_contains_only_specified_chars?(String.t(), [String.t(), ...]) :: boolean
  def string_contains_only_specified_chars?(string, list)
      when is_binary(string) and is_list(list) do
    string
    |> String.graphemes()
    |> Enum.reduce(true, fn letter, acc -> letter in list && acc end)
  end

  @doc """
  Checks if a string is of a specified length or not.

  ## Examples

      iex> Validations.string_expected_length?("abc", 3)
      true

      iex> Validations.string_expected_length?("abc", 2)
      false
  """
  @spec string_expected_length?(String.t(), integer) :: boolean
  def string_expected_length?(string, length) when is_binary(string) and is_integer(length) do
    String.length(string) == length
  end
end

Enter fullscreen mode Exit fullscreen mode

Nothing innovative or surprising--just a little something I whipped up that I wanted to share for the potential benefit of others.

💖 💪 🙅 🚩
olddutchcap
Onorio Catenacci

Posted on April 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

A Quick Utility Module
elixir A Quick Utility Module

April 30, 2024