From bf1175f22c5ca3ae8a7ffd72a6727887bd769bff Mon Sep 17 00:00:00 2001 From: William Casarin Date: Sun, 16 Jul 2023 15:23:26 -0700 Subject: [PATCH] markdown: add some helpers for counting markdown words Will use this in the new word counter --- damus/Views/NoteContentView.swift | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/damus/Views/NoteContentView.swift b/damus/Views/NoteContentView.swift index 11be79a6..28444e7f 100644 --- a/damus/Views/NoteContentView.swift +++ b/damus/Views/NoteContentView.swift @@ -666,3 +666,35 @@ struct NoteContentView_Previews: PreviewProvider { } +func count_words(_ s: String) -> Int { + return s.components(separatedBy: .whitespacesAndNewlines).count +} + +func count_inline_nodes_words(nodes: [InlineNode]) -> Int { + return nodes.reduce(0) { words, node in + switch node { + case .text(let words): + return count_words(words) + case .emphasis(let children): + return words + count_inline_nodes_words(nodes: children) + case .strong(let children): + return words + count_inline_nodes_words(nodes: children) + case .strikethrough(let children): + return words + count_inline_nodes_words(nodes: children) + case .softBreak, .lineBreak, .code, .html, .image, .link: + return words + } + } +} + +func count_markdown_words(blocks: [BlockNode]) -> Int { + return blocks.reduce(0) { words, block in + switch block { + case .paragraph(let content): + return words + count_inline_nodes_words(nodes: content) + case .blockquote, .bulletedList, .numberedList, .taskList, .codeBlock, .htmlBlock, .heading, .table, .thematicBreak: + return words + } + } +} +