Skip to content

Instantly share code, notes, and snippets.

@chase-lambert
Last active May 17, 2023 00:44
Show Gist options
  • Save chase-lambert/8a51f9e5bb9eccb0e15a7f0fdea94297 to your computer and use it in GitHub Desktop.
Save chase-lambert/8a51f9e5bb9eccb0e15a7f0fdea94297 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo challenge: 22.08.21
(ns format-markdown-table
(:require [clojure.string :as s]))
(defn format-column [column width]
(for [row column
:let [word (s/trim row)
new-word (str "| " (format (str "%-" (dec width) "s") word))
dashes (str "| " (apply str (repeat (- width 2) "-")) " ")]]
(if (= (second word) \-)
dashes
new-word)))
(defn format-markdown-table [markdown-string]
(let [rows (s/split-lines markdown-string)
split-rows (map rest
(map #(s/split % #"\|") rows))
columns (apply map vector split-rows)
new-columns (for [column columns
:let [width (apply max
(map count column))]]
(format-column column width))
new-rows (apply map vector new-columns)]
(reduce (fn [s row]
(str s (apply str row) "|\n"))
""
new-rows)))
(def input-markdown
"| Syntax | Description |
| --- | ----------- |
| Header | Title |
| Paragraph | Text |")
(format-markdown-table input-markdown)
; "| Syntax | Description |
; | --------- | ----------- |
; | Header | Title |
; | Paragraph | Text |"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment