I’m currently working on an application that require me to get the year out of a label.
They appear in different ways. It’s never consistent:
examples = [
"February 2015 Part 1",
"2014 Part 2 February",
"February 2015",
"2015 Feb"
]
I need to separate them out so the year and label is like this
expected_result = [
%{"label" => "February Part 1", "year" => "2015"},
%{"label" => "Part 2 February", "year" => "2014"},
%{"label" => "February", "year" => "2015"},
%{"label" => "Feb", "year" => "2015"}
]
Here is my implementation
defmodule ViewHelper do
def get_label_with_year(sentence) do
list_of_words = String.split(sentence, " ")
year = get_year(list_of_words)
label =
list_of_words
|> Enum.reject(fn(word) -> word == year end)
|> Enum.join(" ")
%{}
|> Map.put_new("label", label)
|> Map.put_new("year", year)
end
def get_year(list_of_words) do
[year] = list_of_words
|> Enum.map(fn(x) -> Integer.parse(x) end)
|> Enum.filter(fn(x) -> is_tuple(x) end)
|> Enum.filter(fn({num, _}) -> String.length(to_string(num)) == 4 end)
|> Enum.map(fn({num, _}) -> to_string(num) end)
year
end
end
and my test file
defmodule ViewHelperTest do
use ExUnit.Case
doctest ViewHelper
test "get_label_with_year" do
examples = [
"February 2015 Part 1",
"2014 Part 2 February",
"February 2015",
"2015 Feb"
]
expected_result = [
%{"label" => "February Part 1", "year" => "2015"},
%{"label" => "Part 2 February", "year" => "2014"},
%{"label" => "February", "year" => "2015"},
%{"label" => "Feb", "year" => "2015"}
]
my_test = Enum.map(examples, fn(x) -> ViewHelper.get_label_with_year(x) end)
assert my_test == expected_result
end
end
Everything works. However…
I feel like this implementation is not the best way of writing this.
Could this be written differently so its easier to read? Am I overthinking this?
My intuition tells me this could be written differently so its much easier to understand in the future OR for someone else who will eventually look at this code. Looking for feedback and/or concepts on how to approach this differently (i.e. pattern matching, reducer)