1
\$\begingroup\$
  def age_post(post) do

    birthday = Timex.date({post.birthday_year, post.birthday_month, post.birthday_day})
    now = Date.now

    years = Timex.diff(now, birthday, :years)

    Integer.to_string(years) <> " ans"

  end

I'm quite new with the elixir language, I'm pretty sure you can get the same result than that code in one line.

\$\endgroup\$
3
\$\begingroup\$

You could cut out some of those intermediate variables using the pipeline operator: |>

def age_post(post) do
  birthday = Timex.date({post.birthday_year, post.birthday_month, post.birthday_day})

  (Date.now |> Timex.diff(birthday, :years) |> Integer.to_string) <> " ans"
end
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

If you really want to shorten it, I wouldn't know why you couldn't throw everything together:

def age_post(post) do
  Integer.to_string(Timex.diff(Date.now, Timex.date({post.birthday_year, post.birthday_month, post.birthday_day}), :years)) <> " ans"
end

However, that's absolutely unreadable.

Please re-consider what's really important to you. If this would be code for the company you work for and they'd review your code (and any company-code should be reviewed before being used in production), they wouldn't ask it to be shorter. They'd ask it to be clear.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ well, this code smells imperative code, I'm wondering if it's possible to "translate" that code in functional code. \$\endgroup\$ – Jeremie Ges May 1 '16 at 16:50
  • \$\begingroup\$ @JeremieGes It definitely smells like something, but the original code you posted is by far not the worst way of implementing it. You asked for short, so I helped you out with that. Now it's less repetitive, but harder to maintain. If imperative vs functional is a problem you encounter, feel free to post a new question pointing back to this question with what you really want to improve. \$\endgroup\$ – Mast May 1 '16 at 16:58
  • \$\begingroup\$ Can't you just edit your post and add an exemple of what I'm reaching to do with a functional mindset ? \$\endgroup\$ – Jeremie Ges May 1 '16 at 17:09
  • \$\begingroup\$ @JeremieGes Like |> DateFormat.format!(date, "%a, %d %m %Y %T %Z", :strftime)? \$\endgroup\$ – Mast May 1 '16 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.