Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for markdown text #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions lib/reading_time.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,50 @@ defmodule ReadingTime do

@split_pattern [" ", "\n", "\r", "\t"]
@words_per_minute 200
@markdown_words [
# ignore headers
~r/#+/,
~r/(==)+/,
~r/(--)+/,
# ingore boxed text
~r/>+/,
# ignore unordered lists
~r/-/,
~r/(\*)/,
~r/(\+)/,
# ignore horizontal rules
~r/---+/,
~r/\*\*(\*)+/,
~r/___+/,
]

defp markdown_word?(word) do
Enum.any?(
@markdown_words,
fn md_word ->
Regex.match?(md_word, word)
end
)
end

defp ignore_format_words(words, :text) do
words
end

defp ignore_format_words(words, :markdown) do
words
|> Enum.filter(
fn word ->
!markdown_word?(word)
end
)
end

@spec time(
String.t(),
words_per_minute: non_neg_integer(),
split_pattern: nonempty_list(String.t())
split_pattern: nonempty_list(String.t()),
format: atom()
) :: number
@doc """
Returns the time in minutes for a given string.
Expand All @@ -26,10 +65,11 @@ defmodule ReadingTime do
def time(string, opts \\ []) do
words_per_minute = Keyword.get(opts, :words_per_minute, @words_per_minute)
split_pattern = Keyword.get(opts, :split_pattern, @split_pattern)

text_format = Keyword.get(opts, :text_format, :text)
words =
string
|> String.split(split_pattern, trim: true)
|> ignore_format_words(text_format)
|> length

minutes =
Expand Down
32 changes: 32 additions & 0 deletions test/reading_time_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,36 @@ defmodule ReadingTimeTest do
) * long_text_multiplier
end
end

property "Markdown formatters get ignored" do
text = "
# This is a header1.

## This is a header2.

This is also a header1.
==

This is also a header2.
--

> This is a blockquote
>> This is a nested blockquote
>> # This is a header1 inside a blockquote

---

- List1
+ List2
* List3

***

___

"
actual_words = 37
assert ReadingTime.time(text, words_per_minute: 1, text_format: :markdown) == actual_words
end

end