improve note_title/1
This commit is contained in:
parent
25abb772f6
commit
b2e1b3ebc5
2 changed files with 53 additions and 1 deletions
|
@ -67,7 +67,31 @@ defmodule Chiya.Notes.Note do
|
|||
end
|
||||
|
||||
def note_title(note_content) do
|
||||
String.slice(note_content, 0..25)
|
||||
max_length = 25
|
||||
max_words = 7
|
||||
length = String.length(note_content)
|
||||
|
||||
cond do
|
||||
length <= max_length ->
|
||||
note_content
|
||||
|
||||
String.contains?(note_content, ".") ->
|
||||
note_content
|
||||
|> String.split(".")
|
||||
|> List.first()
|
||||
|
||||
true ->
|
||||
note_content
|
||||
|> String.split(" ")
|
||||
|> Enum.reduce_while([], fn word, list ->
|
||||
if Enum.count(list) < max_words do
|
||||
{:cont, list ++ [word]}
|
||||
else
|
||||
{:halt, list}
|
||||
end
|
||||
end)
|
||||
|> Enum.join(" ")
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
|
|
28
test/chiya/note_test.exs
Normal file
28
test/chiya/note_test.exs
Normal file
|
@ -0,0 +1,28 @@
|
|||
defmodule Chiya.NoteTest do
|
||||
use Chiya.DataCase
|
||||
alias Chiya.Notes.Note
|
||||
|
||||
@content1 "This is a short title"
|
||||
@content2 "This is a title that is a lot longer than the first and does not contain a dot"
|
||||
@content3 "This is a title. It contains dots and should be cut at the first of the dots."
|
||||
@content4 "This used to be some funny title"
|
||||
|
||||
describe "note_title" do
|
||||
test "returns a short text completely" do
|
||||
assert Note.note_title(@content1) == @content1
|
||||
end
|
||||
|
||||
test "returns a longer text until 7 words " do
|
||||
title = Note.note_title(@content2)
|
||||
assert title == "This is a title that is a"
|
||||
|
||||
title = Note.note_title(@content4)
|
||||
assert title == "This used to be some funny title"
|
||||
end
|
||||
|
||||
test "returns a longer text until the first dot" do
|
||||
title = Note.note_title(@content3)
|
||||
assert title == "This is a title"
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue