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.109 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.108 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.107 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.106 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.105 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.104 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.103 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.102 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.101 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.100 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.99 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.98 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.97 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.96 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.95 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.94 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.93 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.92 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.91 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.90 tracks/elixir/exercises/isbn-verifier/example.exs