-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.exs
55 lines (45 loc) · 1.44 KB
/
example.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
defmodule Teenager do
@doc """
Answers to `hey` like a teenager.
## Examples
iex> Teenager.hey("")
"Fine. Be that way!"
iex> Teenager.hey("Do you like math?")
"Sure."
iex> Teenager.hey("HELLO!")
"Woah, chill out!"
iex> Teenager.hey("Coding is cool.")
"Whatever."
"""
def hey(input) do
cond do
silent?(input) -> "Fine. Be that way!"
shouting?(input) -> "Woah, chill out!"
question?(input) -> "Sure."
true -> "Whatever."
end
end
defp silent?(input), do: "" == String.strip(input)
defp shouting?(input), do: input == String.upcase(input) && letters?(input)
defp question?(input), do: String.ends_with?(input, "?")
defp letters?(input), do: Regex.match?(%r/[a-zA-Z]+/, input)
end
# Another approach which abstracts knowing about string categories
# away from Teenager and into a single responsibility module
defmodule Message do
def silent?(input), do: "" == String.strip(input)
def shouting?(input), do: input == String.upcase(input) && letters?(input)
def question?(input), do: String.ends_with?(input, "?")
defp letters?(input), do: Regex.match?(%r/[a-zA-Z]+/, input)
end
defmodule Teenager do
import Message, only: [silent?: 1, shouting?: 1, question?: 1]
def hey(input) do
cond do
silent?(input) -> "Fine. Be that way!"
shouting?(input) -> "Woah, chill out!"
question?(input) -> "Sure."
true -> "Whatever."
end
end
end