Skip to content

Instantly share code, notes, and snippets.

@zk
Forked from dakrone/core.clj
Created November 22, 2011 05:16
Show Gist options
  • Save zk/1384951 to your computer and use it in GitHub Desktop.
Save zk/1384951 to your computer and use it in GitHub Desktop.
Collapse page results into a lazy-seq that only fetches when needed
(ns lazywindow.core)
(def page-size 5)
(defn get-page
"Retrieve a vector of results for a page"
[page-num]
(Thread/sleep 50)
;; this is used to simulate actually getting a page of results
(cond
(= page-num 0) [:a :b :c :d :f]
(= page-num 1) [:g :h :i :j :k]
(= page-num 2) [:l :m :n :o :p]
(= page-num 3) [:q :r :s :t :u]))
(defn get-result
"Given a result index, return that result"
[index]
(let [page (int (Math/floor (/ index page-size)))
offset (mod index page-size)]
(get (get-page page) offset nil)))
(defn results
"Return a lazy-seq of all results"
([] (results 0))
([n] (lazy-seq
(when-let [next (get-result n)]
(cons next (results (inc n)))))))
(def rs (results))
(println (take 30 rs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment