Create a gist now

Instantly share code, notes, and snippets.

line-seq in cljs
;; This is a macro, and must be in clojure. It's name and location is the same as
;; the cljs file, except with a .clj extension.
(ns cljs-made-easy.line-seq
(:refer-clojure :exclude [with-open]))
(defmacro with-open [bindings & body]
(assert (= 2 (count bindings)) "Incorrect with-open bindings")
`(let ~bindings
(try
(do ~@body)
(finally
(.closeSync cljs-made-easy.line-seq/fs ~(bindings 0))))))
;;--------------------------------------------------------------------------------
;; This is the normal cljs file
(ns cljs-made-easy.line-seq
(:require clojure.string)
(:require-macros [cljs-made-easy.line-seq :refer [with-open]]))
(def fs (js/require "fs"))
(defn- read-chunk [fd]
(let [length 128
b (js/Buffer. length)
bytes-read (.readSync fs fd b 0 length nil)]
(if (> bytes-read 0)
(.toString b "utf8" 0 bytes-read))))
(defn line-seq
([fd]
(line-seq fd nil))
([fd line]
(if-let [chunk (read-chunk fd)]
(if (re-find #"\n" (str line chunk))
(let [lines (clojure.string/split (str line chunk) #"\n")]
(if (= 1 (count lines))
(lazy-cat lines (line-seq fd))
(lazy-cat (butlast lines) (line-seq fd (last lines)))))
(recur fd (str line chunk)))
(if line
(list line)
()))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment