defmodule MicrowavepropWeb.LiveHelpers do
  @moduledoc """
  Small helpers shared across LiveView modules. Use sparingly — most
  view-specific logic belongs in its own LiveView.
  """

  @doc """
  Parses a value into a float, returning `default` for nil, empty, or
  unparseable input. Accepts strings, numbers, or any value with a
  `String.Chars` impl.
  """
  @spec parse_float(term(), float()) :: float()
  def parse_float(nil, default), do: default
  def parse_float("", default), do: default

  def parse_float(value, default) do
    case value |> to_string() |> Float.parse() do
      {n, _} -> n
      :error -> default
    end
  end

  @doc """
  Parses a value into an integer, returning `default` for nil, empty,
  or unparseable input.
  """
  @spec parse_int(term(), integer()) :: integer()
  def parse_int(nil, default), do: default
  def parse_int("", default), do: default

  def parse_int(value, default) do
    case value |> to_string() |> Integer.parse() do
      {n, _} -> n
      :error -> default
    end
  end
end
