Skip to content

Commit

Permalink
Add to_float_or/2
Browse files Browse the repository at this point in the history
  • Loading branch information
ByeongUkChoi committed Apr 18, 2022
1 parent eb8003d commit ab9379e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
65 changes: 59 additions & 6 deletions lib/transformer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ defmodule Transformer do
iex> Transformer.to_integer_or("a", nil)
nil
iex> Transformer.to_integer_or("a", & &1 <> &1)
"aa"
iex> Transformer.to_integer_or("a", &{:error, &1})
{:error, "a"}
"""
@spec to_integer_or(integer() | String.t() | nil, any()) :: integer() | any()
@spec to_integer_or(any(), any()) :: integer() | any()
def to_integer_or(value, substitute \\ & &1)

def to_integer_or(value, _substitute) when is_integer(value) do
Expand Down Expand Up @@ -73,10 +73,10 @@ defmodule Transformer do
iex> Transformer.to_integer_list_or([1, 2])
[1, 2]
iex> Transformer.to_integer_list_or(["a", 2], nil)
[nil, 2]
iex> Transformer.to_integer_list_or(["a", 2], &{:error, &1})
[{:error, "a"}, 2]
"""
@spec to_integer_list_or(String.t() | list(), any(), String.t()) :: list()
@spec to_integer_list_or(any(), any(), String.t()) :: list()
def to_integer_list_or(value, substitute \\ & &1, split_pattern \\ ",")

def to_integer_list_or(value, substitute, split_pattern) when is_binary(value) do
Expand All @@ -88,4 +88,57 @@ defmodule Transformer do
def to_integer_list_or(value, substitute, _) when is_list(value) do
value |> Enum.map(&to_integer_or(&1, substitute))
end

@doc """
Convert to float without error.
If it cannot be converted, it returns a substitute.
## Examples
iex> Transformer.to_float_or(1)
1.0
iex> Transformer.to_float_or(1.2)
1.2
iex> Transformer.to_float_or("2")
2.0
iex> Transformer.to_float_or("a")
"a"
iex> Transformer.to_float_or("a", nil)
nil
iex> Transformer.to_float_or("a", &{:error, &1})
{:error, "a"}
"""
@spec to_float_or(any(), any()) :: float() | any()
def to_float_or(value, substitute \\ & &1)

def to_float_or(value, _substitute) when is_float(value) do
value
end

def to_float_or(value, _substitute) when is_integer(value) do
value * 1.0
end

def to_float_or(value, substitute) when is_binary(value) do
try do
String.to_float(value)
rescue
_ ->
try do
String.to_integer(value) * 1.0
rescue
_ -> to_substitute(value, substitute)
end
end
end

def to_float_or(value, substitute) do
to_substitute(value, substitute)
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
defmodule Transformer.MixProject do
use Mix.Project

@version "0.0.1"
@version "0.0.2"
@source_url "https://github.com/ByeongUkChoi/transformer"

def project do
Expand Down

0 comments on commit ab9379e

Please sign in to comment.