Sha256: fd46f3487f683a0e21f752358c6b10500c5c1471126680bf8a02b57fb925aff7

Contents?: true

Size: 783 Bytes

Versions: 69

Compression:

Stored size: 783 Bytes

Contents

defmodule BracketPush do
  @brackets %{
    "{" => "}",
    "(" => ")",
    "[" => "]"
  }

  @doc """
  Check that all the brackets and braces in the string are matched correctly, and nested correctly
  """
  @spec check_brackets(String.t()) :: boolean
  def check_brackets(str) do
    str
    |> String.replace(~r/[^\{\}\[\]\(\)]/, "")
    |> String.codepoints()
    |> check([])
  end

  defp check([], []), do: true
  defp check([], _), do: false

  defp check([h | t], acc) do
    cond do
      Map.has_key?(@brackets, h) ->
        check(t, [Map.get(@brackets, h) | acc])

      Enum.empty?(acc) and !Map.has_key?(@brackets, h) ->
        false

      h != hd(acc) ->
        false

      h == hd(acc) ->
        check(t, tl(acc))

      true ->
        true
    end
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/bracket-push/example.exs