Larme

Untitled

Nov 29th, 2021 (edited)
575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.96 KB | None | 0 0
  1. func tokenizer() {
  2.  
  3.     let initialStringToSend = "TranscribeGlass shows closed captions from any source in your field of view veryveryveryveryveryverylonglongword"
  4.     let characterPerLine = 18
  5.  
  6.  
  7.     func wrap(text: String, with maximumCharacterPerLine: Int) -> [String] {
  8.         let components = text.components(separatedBy: .whitespacesAndNewlines)
  9.         let output = components.reduce(into: [String]()) { result, word in
  10.             guard let last = result.last else {
  11.                 result.append(word)
  12.                 return
  13.             }
  14.             let candidate = last + " " + word
  15.             if candidate.count <= maximumCharacterPerLine {
  16.                 result[result.count - 1] = candidate
  17.             } else if word.count <= maximumCharacterPerLine {
  18.                 result.append(word)
  19.             } else {
  20.                 //Word is too big, we chunk it
  21.                 let chunks: [String] = stride(from: 0, to: word.count, by: maximumCharacterPerLine).map {
  22.                     let start = word.index(word.startIndex, offsetBy: $0)
  23.                     let end = word.index(start, offsetBy: maximumCharacterPerLine, limitedBy: word.endIndex) ?? word.endIndex
  24.                     return String(word[start..<end])
  25.                 }
  26.                 chunks.forEach { result.append($0) }
  27.             }
  28.         }
  29.         return output
  30.     }
  31.  
  32.     let result = wrap(text: initialStringToSend, with: characterPerLine)
  33.     print("Result:")
  34.     result.forEach { print($0) }
  35.  
  36.     let expected = """
  37.    TranscribeGlass
  38.    shows closed
  39.    captions from any
  40.    source in your
  41.    field of view
  42.    """
  43.     print("Expected:\n\(expected)")
  44. }
  45.  
  46. Outputs:
  47.  
  48. Result:
  49. TranscribeGlass
  50. shows closed
  51. captions from any
  52. source in your
  53. field of view
  54. veryveryveryveryve
  55. ryverylonglongword
  56.  
  57. Expected:
  58. TranscribeGlass
  59. shows closed
  60. captions from any
  61. source in your
  62. field of view
  63. //Side note, veryveryveryveryveryverylonglongword isn't in the expected output
Add Comment
Please, Sign In to add comment