less than 1 minute read

Code

(defn limit-offset
  "Limit and offset a collection

   **Arguments**

   * `coll` - A collection to limit and offset
   * `options` - A map containing the following keys:
     * `:offset` - The offset to start from (default: 0)
     * `:limit` - The maximum number of elements to return (default: the number of elements in the collection)

   **Usage**

   ```clojure
   (limit-offset (range 1 11) {:offset 5 :limit 10}) => (6 7 8 9 10 11 12 13 14 15)
   (limit-offset (range 1 11) {:limit 3}) => (1 2 3)
   (limit-offset (range 1 11) {:offset 5}) => (6 7 8 9 10)
   (limit-offset (range 1 11) {}) => (1 2 3 4 5 6 7 8 9 10)
   ```
  "

  [coll options]
  (->> coll
       (drop (:offset options 0))
       (take (:limit options (count coll)))))

(limit-offset (range 1 101) {:offset 5 :limit 10})

(limit-offset (range 1 101) {:limit 10})

(limit-offset (range 1 11) {:offset 5})

(limit-offset (range 1 11) {:offset 25 :limit 5})

(limit-offset (range 1 11) {})

(limit-offset (range 1 11) {:offset 5 :limit nil}) ;; throws error

Updated: