Skip to content

Commit a8fb504

Browse files
thomasmulvaneyswannodette
authored andcommitted
CLJS-1784 - nth doesn't throw on strings or arrays
nth now throws on arrays and strings when n is out of bounds.
1 parent 7e90ad5 commit a8fb504

2 files changed

Lines changed: 21 additions & 8 deletions

File tree

src/main/cljs/cljs/core.cljs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1742,7 +1742,7 @@ reduces them without incurring seq initialization"
17421742
([coll n]
17431743
(cond
17441744
(not (number? n))
1745-
(throw (js/Error. "index argument to nth must be a number"))
1745+
(throw (js/Error. "Index argument to nth must be a number"))
17461746

17471747
(nil? coll)
17481748
coll
@@ -1751,12 +1751,14 @@ reduces them without incurring seq initialization"
17511751
(-nth ^not-native coll n)
17521752

17531753
(array? coll)
1754-
(when (< n (.-length coll))
1755-
(aget coll n))
1754+
(if (and (>= n 0) (< n (.-length coll)))
1755+
(aget coll n)
1756+
(throw (js/Error. "Index out of bounds")))
17561757

17571758
(string? coll)
1758-
(when (< n (.-length coll))
1759-
(.charAt coll n))
1759+
(if (and (>= n 0) (< n (.-length coll)))
1760+
(.charAt coll n)
1761+
(throw (js/Error. "Index out of bounds")))
17601762

17611763
(implements? ISeq coll)
17621764
(linear-traversal-nth coll n)
@@ -1770,7 +1772,7 @@ reduces them without incurring seq initialization"
17701772
([coll n not-found]
17711773
(cond
17721774
(not (number? n))
1773-
(throw (js/Error. "index argument to nth must be a number."))
1775+
(throw (js/Error. "Index argument to nth must be a number."))
17741776

17751777
(nil? coll)
17761778
not-found
@@ -1779,12 +1781,12 @@ reduces them without incurring seq initialization"
17791781
(-nth ^not-native coll n not-found)
17801782

17811783
(array? coll)
1782-
(if (< n (.-length coll))
1784+
(if (and (>= n 0) (< n (.-length coll)))
17831785
(aget coll n)
17841786
not-found)
17851787

17861788
(string? coll)
1787-
(if (< n (.-length coll))
1789+
(if (and (>= n 0) (< n (.-length coll)))
17881790
(.charAt coll n)
17891791
not-found)
17901792

src/test/cljs/cljs/core_test.cljs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3293,6 +3293,17 @@
32933293
(is (= (foo-fn foo {:a 1 :b 2})
32943294
{:c 3}))))
32953295

3296+
(deftest test-cljs-1748
3297+
(is (thrown? js/Error (nth (array 0 1 2) 3)))
3298+
(is (thrown? js/Error (nth (array 0 1 2) -1)))
3299+
(is (= (nth (array 0 1 2) 3 :not-found) :not-found))
3300+
(is (= (nth (array 0 1 2) -1 :not-found) :not-found))
3301+
3302+
(is (thrown? js/Error (nth "012" 3)))
3303+
(is (thrown? js/Error (nth "012" -1)))
3304+
(is (= (nth "012" 3 :not-found) :not-found))
3305+
(is (= (nth "012" -1 :not-found) :not-found)))
3306+
32963307
(comment
32973308
;; ObjMap
32983309
;; (let [ks (map (partial str "foo") (range 500))

0 commit comments

Comments
 (0)