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.159 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.158 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.157 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.156 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.155 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.154 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.153 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.152 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.151 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.150 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.149 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.148 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.147 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.146 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.145 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.144 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.143 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.142 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.141 tracks/elixir/exercises/bracket-push/example.exs
trackler-2.2.1.140 tracks/elixir/exercises/bracket-push/example.exs