/
String+.swift
73 lines (63 loc) · 1.9 KB
/
String+.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// File.swift
//
//
// Created by Yusuke Hosonuma on 2022/03/28.
//
import Foundation
extension String {
func extractEnglishText() -> String {
if isEmpty {
return self
}
return lines
.compactMap(\.removeCommentToken)
.reduce(into: []) { lines, newLine in
func isCodeLine() -> Bool {
lines.last?.isListLine == false && newLine.starts(with: " ")
}
if newLine.isEmpty {
lines.append("\n")
} else if lines.last == "\n" || newLine.isListLine || isCodeLine() {
lines.append(contentsOf: ["\n", newLine]) // Join with new-line
} else {
lines.append(" " + newLine.trimed()) // Join to one-line
}
}
.joined()
.replacingOccurrences(of: "``", with: "`")
.trimed()
}
// e.g.
// ```
// - Parameters:
// - start: A valid index of the collection.
// ```
private var isListLine: Bool {
if let firstToken = removeIndent().first {
return ["-", "@"].contains(firstToken)
} else {
return false
}
}
// Trimming space and documentation comment token.
private var removeCommentToken: String? {
let line = removeIndent()
if line.hasPrefix("/**") || line.hasPrefix("*/") {
return nil
} else {
return ["/// ", "///", "* ", "*"].reduce(line) {
$0.replacingOccurrences(of: $1, with: "")
}
}
}
private var lines: [String] {
split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
}
private func trimed() -> String {
trimmingCharacters(in: .whitespaces)
}
private func removeIndent() -> String {
String(drop { $0 == " " })
}
}