Last active
December 27, 2020 07:47
-
-
Save eksperimental/6de64dd3d384d5cdb255 to your computer and use it in GitHub Desktop.
Kernel.to_boolean/1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Kernel do | |
@doc """ | |
Converts any expression to boolean. | |
Returns `true` if `expr` is truthy (ie. it does not evaluate to `nil`, nor `false`), | |
otherwise returns the `false`. | |
Allowed in guard tests. | |
""" | |
@spec to_boolean(Macro.t) :: boolean | |
defmacro to_boolean(expr) do | |
quote do | |
not unquote(expr) in [false, nil] | |
end | |
end | |
end | |
defmodule Kernel.ToBooleanTest do | |
use ExUnit.Case, async: true | |
def has_second_and_third_char?(string) when to_boolean(binary_part(string, 1, 1)) and to_boolean(binary_part(string, 2, 1)), | |
do: true | |
def has_second_and_third_char?(_), | |
do: false | |
test "Kernel.to_boolean/1 in guards" do | |
assert has_second_and_third_char?("f") == false | |
assert has_second_and_third_char?("") == false | |
assert has_second_and_third_char?("fo") == false | |
assert has_second_and_third_char?("foo") == true | |
assert has_second_and_third_char?("foooooo") == true | |
end | |
test "Kernel.to_boolean/1" do | |
assert to_boolean(true) == true | |
assert to_boolean(false) == false | |
assert to_boolean(nil) == false | |
assert to_boolean("") == true | |
assert to_boolean([]) == true | |
assert to_boolean("yes") == true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment