From b2e1b3ebc544e6b60f2e9bb5ba294fa12350a154 Mon Sep 17 00:00:00 2001 From: Inhji Date: Tue, 4 Jul 2023 22:17:02 +0200 Subject: [PATCH] improve note_title/1 --- lib/chiya/notes/note.ex | 26 +++++++++++++++++++++++++- test/chiya/note_test.exs | 28 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 test/chiya/note_test.exs diff --git a/lib/chiya/notes/note.ex b/lib/chiya/notes/note.ex index 9c51490..63cc753 100644 --- a/lib/chiya/notes/note.ex +++ b/lib/chiya/notes/note.ex @@ -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 diff --git a/test/chiya/note_test.exs b/test/chiya/note_test.exs new file mode 100644 index 0000000..a3ada46 --- /dev/null +++ b/test/chiya/note_test.exs @@ -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 \ No newline at end of file