repl.it
@shahinism/

Compress String Clojure

Clojure

No description

fork
loading
Files
  • main.clj
main.clj
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
(ns compress-clj.core
    (:require [clojure.string :refer [join]])
    (:use clojure.test))

(defn group-chars
  [string]
  (partition-by identity string))

(defn create-part
  [group]
  (let [length (count group)
        char (first group)]
    (if (= length 1)
      (str char)
      (str char length))
    ))

(defn compress
  "Compress string."
  [string]
  (let [compressed (join "" (map create-part (group-chars string)))]
    (if (= (count compressed) (count string))
      string
      compressed)))

(deftest a-test
  (testing "empty, is empty"
    (is (= (compress "") "")))
  (testing "doesn't compress fine strings"
    (is (= (compress "ABC") "ABC"))
    (is (= (compress "AABBCC") "AABBCC")))
  (testing "does compress effectively"
    (is (= (compress "AAABCCDDDDE") "A3BC2D4E"))
    (is (= (compress "BAAACCDDDD") "BA3C2D4"))
    (is (= (compress "AAABAACCDDDD") "A3BA2C2D4"))))

(run-tests)
Clojure 1.8.0 Java HotSpot(TM) 64-Bit Server VM 1.8.0_91-b14
?