Skip to content

Instantly share code, notes, and snippets.

@visibletrap
Last active August 23, 2017 01:02
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 visibletrap/a31e3906ad2e9fade1939e9df1ed0f7e to your computer and use it in GitHub Desktop.
Save visibletrap/a31e3906ad2e9fade1939e9df1ed0f7e to your computer and use it in GitHub Desktop.
(ns indent-tree.core
(:require [clojure.string :as string]))
(defn resolve-insert-path [full-tree level]
(:path
(reduce (fn [{:keys [path tree] :as current} n]
(let [after-last-child-pos (count (second tree))]
(if (= n 1)
(-> current
(update :path into [1 after-last-child-pos])
(dissoc tree))
(let [last-child-pos (dec after-last-child-pos)]
(-> current
(update :path into [1 last-child-pos])
(update :tree get-in [1 last-child-pos]))))))
{:path [] :tree full-tree}
(reverse (range 1 (inc level))))))
(comment
(resolve-insert-path [:root []] 1) ;=> [1 0]
(resolve-insert-path [:root [["a" []]]] 1) ;=> [1 1]
(resolve-insert-path [:root [["a" []]]] 2) ;=> [1 0 1 0]
)
(defn make-node [text] [text []])
(def line->node+level
(comp (juxt (comp make-node #(string/join " " %) rest)
(comp count first))
#(string/split % #" ")))
(comment
(line->node+level "* text") ;=> [["text" []] 1]
(line->node+level "** text") ;=> [["text" []] 2]
)
(defn parse-header [header-string]
(->> header-string
(string/split-lines)
(map line->node+level)
(reduce (fn [tree [node level]]
(assoc-in tree (resolve-insert-path tree level) node))
[:root []])
second))
(comment
(parse-header "* a\n* b\n* c") ;=> [["a" []] ["b" []] ["c" []]]
(parse-header "* a\n** b\n* c") ;=> [["a" [["b" []]]] ["c" []]]
(parse-header "* a\n** b\n** c\n*** d\n* e") ;=> [["a" [["b" []] ["c" [["d" []]]]]] ["e" []]]
(parse-header "* ความสามารถพิเศษ\n* รายวิชา\n** GAT \n** PAT1\n** PAT2\n** อื่น ๆ\n*** ไม่บอก\n*** บอกแล้ว\n** PAT50\n* จำนวนรับ")
;=>
[["ความสามารถพิเศษ" []]
["รายวิชา"
[["GAT" []]
["PAT1" []]
["PAT2" []]
["อื่น ๆ"
[["ไม่บอก" []]
["บอกแล้ว" []]]]
["PAT50" []]]]
["จำนวนรับ" []]]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment