Created
February 8, 2019 20:03
-
-
Save DanielRamosAcosta/f47ea4caebd0cc477bad6fc14f30725b to your computer and use it in GitHub Desktop.
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 StringCalculator do | |
| def has_delimiter?(str) do | |
| String.starts_with?(str, "//") | |
| end | |
| def extract_delimiter(str) do | |
| {String.at(str, 2), String.slice(str, 3..-1)} | |
| end | |
| def replace_whitespace_with_separator(str, separator) do | |
| String.replace(str, "\n", separator, global: true) | |
| end | |
| def string_to_list(str, separator) do | |
| str | |
| |> StringCalculator.replace_whitespace_with_separator(separator) | |
| |> String.split(separator) | |
| end | |
| def parse_string_list([head | tail]) do | |
| [String.to_integer(head) | StringCalculator.parse_string_list(tail)] | |
| end | |
| def parse_string_list([]) do | |
| [] | |
| end | |
| def sum_list([head | tail]) do | |
| head + sum_list(tail) | |
| end | |
| def sum_list([]) do | |
| 0 | |
| end | |
| def calculate(rawString) do | |
| {separator, str} = if StringCalculator.has_delimiter?(rawString) do | |
| StringCalculator.extract_delimiter(rawString) | |
| else | |
| {",", rawString} | |
| end | |
| str | |
| |> StringCalculator.string_to_list(separator) | |
| |> StringCalculator.parse_string_list | |
| |> StringCalculator.sum_list | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment