Avatar of paulfioravanti

paulfioravanti's solution

to Markdown in the Elixir Track

Published at Aug 31 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Refactor a Markdown parser.

The markdown exercise is a refactoring exercise. There is code that parses a given string with Markdown syntax and returns the associated HTML for that string. Even though this code is confusingly written and hard to follow, somehow it works and all the tests are passing! Your challenge is to re-write this code to make it easier to read and maintain while still making sure that all the tests keep passing.

It would be helpful if you made notes of what you did in your refactoring in comments so reviewers can see that, but it isn't strictly necessary. The most important thing is to make the code better!

Running tests

Execute the tests with:

$ mix test

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

markdown_test.exs

defmodule MarkdownTest do
  use ExUnit.Case

  # @tag :pending
  test "parses normal text as a paragraph" do
    input = "This will be a paragraph"
    expected = "<p>This will be a paragraph</p>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "parsing italics" do
    input = "_This will be italic_"
    expected = "<p><em>This will be italic</em></p>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "parsing bold text" do
    input = "__This will be bold__"
    expected = "<p><strong>This will be bold</strong></p>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "mixed normal, italics and bold text" do
    input = "This will _be_ __mixed__"
    expected = "<p>This will <em>be</em> <strong>mixed</strong></p>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "with h1 header level" do
    input = "# This will be an h1"
    expected = "<h1>This will be an h1</h1>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "with h2 header level" do
    input = "## This will be an h2"
    expected = "<h2>This will be an h2</h2>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "with h6 header level" do
    input = "###### This will be an h6"
    expected = "<h6>This will be an h6</h6>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "unordered lists" do
    input = "* Item 1\n* Item 2"
    expected = "<ul><li>Item 1</li><li>Item 2</li></ul>"
    assert Markdown.parse(input) == expected
  end

  @tag :pending
  test "with a little bit of everything" do
    input = "# Header!\n* __Bold Item__\n* _Italic Item_"

    expected =
      "<h1>Header!</h1><ul><li><strong>Bold Item</strong></li><li><em>Italic Item</em></li></ul>"

    assert Markdown.parse(input) == expected
  end
end

test_helper.exs

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule Markdown do
  @header_attribute "#"
  @list_attribute "*"
  @emphasis_attribute "_"
  @strong_attribute String.duplicate(@emphasis_attribute, 2)
  @open_list_item_tag "<li>"
  @close_list_item_tag "</li>"
  @open_ul_tag "<ul>"
  @close_ul_tag "</ul>"
  @open_strong_tag "<strong>"
  @close_strong_tag "</strong>"
  @open_emphasis_tag "<em>"
  @close_emphasis_tag "</em>"
  @open_paragraph_tag "<p>"
  @close_paragraph_tag "</p>"

  @doc """
    Parses a given string with Markdown syntax and returns the associated HTML for that string.

    ## Examples

    iex> Markdown.parse("This is a paragraph")
    "<p>This is a paragraph</p>"

    iex> Markdown.parse("#Header!\n* __Bold Item__\n* _Italic Item_")
    "<h1>Header!</h1><ul><li><em>Bold Item</em></li><li><i>Italic Item</i></li></ul>"
  """
  @spec parse(String.t()) :: String.t()
  def parse(markdown) do
    markdown
    |> String.split("\n")
    |> process([])
    |> Enum.reverse()
    |> Enum.join()
  end

  defp process([], acc), do: acc

  defp process([@header_attribute <> _rest = head | tail], acc) do
    header =
      head
      |> parse_header()
      |> enclose_with_header_tag()

    process(tail, [header | acc])
  end

  defp process([@list_attribute <> _rest | _tail] = lines, acc) do
    {tail, list} = parse_list(lines, [@open_ul_tag])
    process(tail, [list | acc])
  end

  defp process([head | tail], acc) do
    paragraph =
      head
      |> String.split()
      |> join_words_with_tags()
      |> enclose_with_paragraph_tag()

    process(tail, [paragraph | acc])
  end

  defp parse_header(header) do
    [formatting, text] = String.split(header, " ", parts: 2)
    level = String.length(formatting)
    {level, text}
  end

  defp parse_list([@list_attribute <> rest | tail], acc) do
    list_item =
      rest
      |> String.split()
      |> join_words_with_tags()
      |> enclose_with_list_item_tag()

    parse_list(tail, [list_item | acc])
  end

  defp parse_list(lines, acc) do
    list =
      acc
      |> Enum.reverse()
      |> Enum.join()
      |> Kernel.<>(@close_ul_tag)

    {lines, list}
  end

  defp join_words_with_tags(words) do
    words
    |> Enum.map(&replace_md_with_tag/1)
    |> Enum.join(" ")
  end

  defp replace_md_with_tag(word) do
    word
    |> replace_prefix()
    |> replace_suffix()
  end

  defp replace_prefix(@strong_attribute <> rest), do: @open_strong_tag <> rest
  defp replace_prefix(@emphasis_attribute <> rest), do: @open_emphasis_tag <> rest
  defp replace_prefix(word), do: word

  defp replace_suffix(word) do
    cond do
      String.ends_with?(word, @strong_attribute) ->
        String.replace(word, @strong_attribute, @close_strong_tag)

      String.ends_with?(word, @emphasis_attribute) ->
        String.replace(word, @emphasis_attribute, @close_emphasis_tag)

      true ->
        word
    end
  end

  defp enclose_with_header_tag({level, header}) do
    "<h#{level}>" <> header <> "</h#{level}>"
  end

  defp enclose_with_list_item_tag(list_item) do
    @open_list_item_tag <> list_item <> @close_list_item_tag
  end

  defp enclose_with_paragraph_tag(paragraph) do
    @open_paragraph_tag <> paragraph <> @close_paragraph_tag
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?