|
| 1 | +(ns clojure.core-test.take-nth |
| 2 | + (:require [clojure.test :as t :refer [are deftest is testing]] |
| 3 | + [clojure.core-test.portability #?(:cljs :refer-macros :default :refer) [when-var-exists]])) |
| 4 | + |
| 5 | +(when-var-exists take-nth |
| 6 | + (deftest test-take-nth |
| 7 | + (testing "Basic arity-2" |
| 8 | + (are [expected n coll] (= expected (take-nth n coll)) |
| 9 | + (range 0 10 1) 1 (range 10) |
| 10 | + (range 0 10 2) 2 (range 10) |
| 11 | + (range 0 10 3) 3 (range 10) |
| 12 | + '(\C \o \u \e \R \c \s) 2 "Clojure Rocks" ; works on any seq |
| 13 | + () 2 nil)) |
| 14 | + |
| 15 | + ;; 1-arity transducer |
| 16 | + (testing "Arity-1 transducer" |
| 17 | + (are [expected n coll] (= (vec expected) (transduce (take-nth n) conj [] coll)) |
| 18 | + (range 0 10 1) 1 (range 10) |
| 19 | + (range 0 10 2) 2 (range 10) |
| 20 | + (range 0 10 3) 3 (range 10) |
| 21 | + '(\C \o \u \e \R \c \s) 2 "Clojure Rocks" ; works on any seq |
| 22 | + () 2 nil)) |
| 23 | + |
| 24 | + (testing "Negative cases" |
| 25 | + ;; Note: passing a non-positive integer (either zero or |
| 26 | + ;; negative) to the arity-2 version take-nth results in an |
| 27 | + ;; infinite loop. Do not do this: |
| 28 | + #_(take-nth 0 (range 10)) ; infinite loop |
| 29 | + |
| 30 | + ;; But you can pass negative numbers, but not zero, to the |
| 31 | + ;; arity-1 version and it treats it the same as if n was |
| 32 | + ;; positive. If you pass in zero, it throws an exception (see |
| 33 | + ;; below). |
| 34 | + (are [expected n coll] (= (vec expected) (transduce (take-nth n) conj [] coll)) |
| 35 | + (range 0 10 1) -1 (range 10) |
| 36 | + (range 0 10 2) -2 (range 10)) |
| 37 | + |
| 38 | + (is (thrown? #?(:cljs :default :default Exception) |
| 39 | + (seq (take-nth nil (range 10))))) |
| 40 | + (is (thrown? #?(:cljs :default :default Exception) |
| 41 | + (transduce (take-nth nil) conj [] (range 10)))) |
| 42 | + #?(:cljs |
| 43 | + (is (= [] (transduce (take-nth 0) conj [] (range 10)))) |
| 44 | + :default |
| 45 | + (is (thrown? Exception (transduce (take-nth 0) conj [] (range 10)))))))) |
0 commit comments