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.180 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/isbn-verifier/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/isbn-verifier/example.exs