Skip to content

Instantly share code, notes, and snippets.

@maruks
Created May 27, 2015 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maruks/ead86929334dce9e4e12 to your computer and use it in GitHub Desktop.
Save maruks/ead86929334dce9e4e12 to your computer and use it in GitHub Desktop.
(ns sandbox.words
(:require [clojure.string :refer [blank? trim join]]))
(def split-at-chars #{\newline \space \tab})
(defn cut-single-line [text column-length]
(if (> (count text) column-length)
(let [line (drop-while (complement split-at-chars) (reverse text))
length (count line)]
(cond
(zero? length) (take column-length text)
(> length column-length) (reverse (next line))
:else (reverse line)))
text))
(defn words [text column-lenght]
(lazy-seq
(when (seq text)
(let [line (cut-single-line (take (inc column-lenght) text) column-lenght)]
(cons (apply str line) (words (drop (count line) text) column-lenght))))))
(defn format-text [text column-length]
(join \newline (map trim (remove blank? (words text column-length)))))
(ns sandbox.words-test
(:require [clojure.test :refer :all]
[sandbox.words :refer :all]))
(def str1 "1 12 123 1234")
(def str2 "Not only working software,\nbut also well-crafted software")
(def str3 "Pas seulement des logiciels opérationnels,\n mais aussi des logiciels bien conçus.")
(deftest words-test
(is (= '("hello " "world") (words "hello world" 8)))
(is (= '("hello world") (words "hello world" 12)))
(is (= '("hello," " how " "are " "you") (words "hello, how are you" 6)))
(is (= '("hello, how " "are you") (words "hello, how are you" 12)))
(is (= '("1 " "12 " "123" " " "123" "4") (words str1 3)))
(is (= str1 (apply str (words str1 3))))
(is (= str2 (apply str (words str2 4))))
(is (= str3 (apply str (words str3 5)))))
(deftest format-test
(is (= "Not only\nworking\nsoftware,\nbut also\nwell-craf\nted\nsoftware" (format-text str2 9))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment