Sha256: 0c026e7881c67e69397c8ae7a219b58d46675c2467907c84e6a1213974d6c4d6

Contents?: true

Size: 734 Bytes

Versions: 52

Compression:

Stored size: 734 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

52 entries across 52 versions & 1 rubygems

Version Path
trackler-2.2.1.89 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.88 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.87 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.86 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.85 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.84 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.83 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.82 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.81 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.80 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.79 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.78 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.77 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.76 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.75 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.74 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.73 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.72 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.71 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.70 tracks/elixir/exercises/isbn-verifier/example.exs