ycv005
Optimize the inner Match or Conditional Case
For every conditional assignment, every time I need to write a new condition. for example-
ready_for_eligible_account =
cond do
price_plan["standard_plan"]["monthly"] == 0 ->
true
price_plan["standard_plan"]["monthly"] != 0 ->
false
end
validation_msg =
case ready_for_eligible_account do
true ->
"Coupon Validated"
false ->
"Invalid Coupon"
end
How can I do the same in 1 conditional case? Also, tell the general way so that I could handle more than 2 conditional case. Your help will be appreciated.
Marked As Solved
NobbZ
This can be easily rewritten as a simple assignement:
ready = price_plan["standard_plan"]["monthly"] == 0
And this is easier to grasp when written as an if rather than a case:
message = if ready, do: "Coupon Validated", else: "Invalid Coupon"
Also Liked
NobbZ
Your first expression whas of this kind:
result = cond do
condition -> true
not condition -> false
end
Which in its nature is very similar
result = if condition, do: true, else: false
Which can always be simplified to
result = condition
The second one is a bit different, but usually, whenever you have a case matching on true/false only, you usually can just replace it by an if, there might be cases where you want to explicitely true/false rather than truthy/falsey checks, then of course you need the case.
And to be honest, about any 2-clause-case that matches on an exact value rather than binding names, while the other arm uses _ can be rewritten into an if by just using Kernel.===/2 or Kernel.==/2, depending on the semantics you need.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









