Last active
April 24, 2017 23:57
-
-
Save onegrx/0e775d2ead063fa98ab5a36fd59e250c to your computer and use it in GitHub Desktop.
Fetch config from keyword list
This file contains hidden or 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 Config do | |
def get(key, default) do | |
# Sample config | |
vars = [key1: :val1, | |
key2: [nested_key1: :nested_val1, | |
nested_key2: :nested_val2]] | |
get(key, vars, default) | |
end | |
def get(key) do | |
# Sample config | |
vars = [key1: :val1, | |
key2: [nested_key1: :nested_val1, | |
nested_key2: :nested_val2]] | |
get(key, vars, :undef) | |
end | |
defp get([head | tail], config, _) do | |
remaining = get(head, config) | |
get(tail, remaining) | |
end | |
defp get(key, config, default) do | |
case is_list(config) do | |
true -> | |
case config do | |
[] -> default | |
_ -> | |
case hd(config) do | |
{^key, val} -> val | |
_ -> get(key, tl(config)) | |
end | |
end | |
false -> config | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment