Skip to content

Instantly share code, notes, and snippets.

@viebel
Created October 29, 2019 07:14
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 viebel/983676a98aee0991cfb002a67676602f to your computer and use it in GitHub Desktop.
Save viebel/983676a98aee0991cfb002a67676602f to your computer and use it in GitHub Desktop.
(ns viebel.gist-983676a98aee0991cfb002a67676602f.raw.split-expressions
(:require [cljs.tools.reader :as r]
[cljs.tools.reader.reader-types :as rt]
[clojure.string :as s]))
(defn- read-chars
[reader]
(loop [res []]
(if-let [ch (rt/read-char reader)]
(recur (conj res ch))
res)))
(defn reader-content [r]
(apply str (read-chars r)))
(defn first-exp-and-rest [s]
(let [sentinel (js-obj)
reader (rt/string-push-back-reader s)
res (r/read reader false sentinel)]
(if (= sentinel res)
["" ""]
(let [rest-s (reader-content reader)
first-exp (subs s 0 (- (count s) (count rest-s)))]
[(s/replace first-exp #"^[\s\n]*" "")
rest-s]))))
(defn split-expressions [s]
(loop [s s res []]
(if (empty? s)
res
(let [[exp rest-s] (first-exp-and-rest s)]
(if (empty? exp)
(recur rest-s res)
(recur rest-s (conj res exp)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment