Skip to content

Commit e43c6f7

Browse files
committed
CLJS-2799: Handle nth on seqables with negative indexes
This adds a negative-index check to nth, prior to calling linear-traversal-nth. (The check could concievably be done inside linear-traversal-nth, but that would be less efficient as that function recurs on itself and the check would then be made on each loop.)
1 parent 892ed20 commit e43c6f7

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/main/cljs/cljs/core.cljs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1866,7 +1866,9 @@ reduces them without incurring seq initialization"
18661866

18671867
(or (implements? ISeq coll)
18681868
(implements? ISequential coll))
1869-
(linear-traversal-nth coll n)
1869+
(if (neg? n)
1870+
(throw (js/Error. "Index out of bounds"))
1871+
(linear-traversal-nth coll n))
18701872

18711873
(native-satisfies? IIndexed coll)
18721874
(-nth coll n)
@@ -1897,7 +1899,9 @@ reduces them without incurring seq initialization"
18971899

18981900
(or (implements? ISeq coll)
18991901
(implements? ISequential coll))
1900-
(linear-traversal-nth coll n not-found)
1902+
(if (neg? n)
1903+
not-found
1904+
(linear-traversal-nth coll n not-found))
19011905

19021906
(native-satisfies? IIndexed coll)
19031907
(-nth coll n not-found)

src/test/cljs/cljs/core_test.cljs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1566,6 +1566,10 @@
15661566
(is (thrown-with-msg? js/Error #".*Invalid arity: 0" ({})))
15671567
(is (thrown-with-msg? js/Error #".*Invalid arity: 3" ({} 1 2 3))))
15681568

1569+
(deftest test-cljs-2799
1570+
(is (thrown? js/Error (nth (repeat :x) -1)))
1571+
(is (= ::not-found (nth (repeat :x) -1 ::not-found))))
1572+
15691573
(comment
15701574
;; ObjMap
15711575
;; (let [ks (map (partial str "foo") (range 500))

0 commit comments

Comments
 (0)