Avatar of johngradle

johngradle's solution

to Markdown in the Elixir Track

Published at Jul 04 2020 · 0 comments
Instructions
Test suite
Solution

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
  @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(m) do
    String.split(m, "\n")
    |> Enum.map(&process_line/1)
    |> group_list_items([])
    |> Enum.reverse
    |> Enum.join
    # |> IO.inspect
  end

  defp process_line(text) do
    cond do
      String.starts_with?(text, "#") -> add_header(text)
      String.starts_with?(text, "*") -> add_list_item(text)
      true -> add_para(text)
    end
  end

  defp add_header(text) do
    parse_header_md_level(text)
    |> enclose_with_header_tag
  end

  defp add_list_item(list) do
    text = String.split(String.trim_leading(list, "* "))
    "<li>#{join_words_with_tags(text)}</li>"
  end

  defp add_para(text) do
    String.split(text)
    |> enclose_with_paragraph_tag
  end

  defp parse_header_md_level(text) do
    [head | tail] = String.split(text)
    {to_string(String.length(head)), Enum.join(tail, " ")}
  end

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

  defp enclose_with_paragraph_tag(text) do
    "<p>#{join_words_with_tags(text)}</p>"
  end

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

  defp replace_md_with_tag(text) do
    text
    |> replace_prefix_md
    |> replace_suffix_md
  end

  defp replace_prefix_md(w) do
    cond do
      w =~ ~r/^#{"__"}{1}/            -> String.replace(w, ~r/^#{"__"}{1}/, "<strong>", global: false)
      w =~ ~r/^[#{"_"}{1}][^#{"_"}+]/ -> String.replace(w, ~r/_/,           "<em>",     global: false)
      true -> w
    end
  end

  defp replace_suffix_md(w) do
    cond do
      w =~ ~r/#{"__"}{1}$/  -> String.replace(w, ~r/#{"__"}{1}$/, "</strong>")
      w =~ ~r/[^#{"_"}{1}]/ -> String.replace(w, ~r/_/,           "</em>")
      true -> w
    end

  end

  defp group_list_items([], result) do
    result

  end
  defp group_list_items([head | tail], result) do
    if (String.starts_with?(head, "<li>")) do
      result = ["<ul>" | result]
      result = [ head | result]

      list_item( tail, result )
    else
      group_list_items(tail, [head | result])
    end

  end

  defp list_item([], result) do
    ["</ul>" | result]

  end
  defp list_item([head | tail], result) do
    if (String.starts_with?(head, "<li>")) do
      list_item(tail, [head | result])
    else
      result = ["</ul>" | result]
      result = [head | result]
      group_list_items(tail, result )
    end

  end

  # defp patch(l) do
  #   String.replace_suffix(
  #     String.replace(l, "<li>", "<ul>" <> "<li>", global: false),
  #     "</li>",
  #     "</li>" <> "</ul>"
  #   )
  # end

end

Community comments

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

johngradle's Reflection

FAILS

# @tag :pending
test "correctly starts/finishes multiple unordered lists" do
input = "# header 1\n* Item 1\n* Item 2\n# header 2\n* Item A\n* Item B"
expected = "

header 1


  • Item 1

  • Item 2

header 2


  • Item A

  • Item B

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