Last active
September 25, 2022 19:58
-
-
Save wayne5540/a827b7ac100a934186199008cff51276 to your computer and use it in GitHub Desktop.
Ruby implementation for Elixir cond
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 Validator do | |
def validate_age(age) do | |
cond do | |
age < 18 -> "Under 18" | |
age < 21 -> "Under 21" | |
true -> "Adult" | |
end | |
end | |
end |
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
class Elixir | |
def cond(*assertions) | |
return assertions.compact.first | |
end | |
def if(assertion, block) | |
return block.call() if assertion == true | |
end | |
end |
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
RSpec.describe Elixir do | |
let(:elixir) { described_class.new } | |
describe "cond" do | |
specify do | |
result = elixir.cond( | |
elixir.if(false, -> { return 1 }), | |
elixir.if(true, -> { return 2 }), | |
elixir.if(true, -> { return 3 }) | |
) | |
expect(result).to eq(2) | |
end | |
end | |
describe "if" do | |
specify do | |
result = elixir.if(true, -> { 1 }) | |
expect(result).to eq(1) | |
end | |
specify do | |
result = elixir.if(false, -> { 1 }) | |
expect(result).to eq(nil) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment