Sha256: a122dc52de127eeaef32b5bad21286f4b0cf149dbd1c0f3ad093bfbfa47f5a7e

Contents?: true

Size: 735 Bytes

Versions: 69

Compression:

Stored size: 735 Bytes

Contents

defmodule ISBNVerifier do
  @doc """
    Checks if a string is a valid ISBN-10 identifier

    ## Examples

      iex> ISBNVerifier.isbn?("3-598-21507-X")
      true

      iex> ISBNVerifier.isbn?("3-598-2K507-0")
      false

  """
  @spec isbn?(String.t()) :: boolean
  def isbn?(isbn) do
    if Regex.match?(~r/^(\d-?){9}(\d|X)$/, isbn) do
      checksum =
        isbn
        |> String.replace("-", "")
        |> String.graphemes()
        |> Enum.zip(10..1)
        |> Enum.map(&checksum_weighting/1)
        |> Enum.sum()

      rem(checksum, 11) == 0
    else
      false
    end
  end

  defp checksum_weighting({"X", 1}), do: 10

  defp checksum_weighting({digit, weight}) do
    String.to_integer(digit) * weight
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.119 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.118 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.117 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.116 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.115 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.114 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.113 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.111 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.110 tracks/elixir/exercises/isbn-verifier/example.exs