Skip to content

Commit

Permalink
drop with a negative count now drops from the end
Browse files Browse the repository at this point in the history
  • Loading branch information
ianthehenry committed Apr 24, 2023
1 parent d9ed7a7 commit 54b54f8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
13 changes: 7 additions & 6 deletions src/boot/boot.janet
Original file line number Diff line number Diff line change
Expand Up @@ -1133,16 +1133,17 @@
(take-until (complement pred) ind))

(defn drop
``Drop the first n elements in an indexed or bytes type. Returns a new tuple or string
instance, respectively.``
``Drop the first `n elements in an indexed or bytes type. Returns a new tuple or string
instance, respectively. If `n` is negative, drops the last `n` elements instead.``
[n ind]
(def use-str (bytes? ind))
(def f (if use-str string/slice tuple/slice))
(def len (length ind))
# make sure start is in [0, len]
(def m (if (> n 0) n 0))
(def start (if (> m len) len m))
(f ind start -1))
(def [start end]
(if (>= n 0)
[(min n len) len]
[0 (max 0 (+ len n))]))
(f ind start end))

(defn drop-until
"Same as `(drop-while (complement pred) ind)`."
Expand Down
9 changes: 7 additions & 2 deletions test/suite0005.janet
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,13 @@
(assert (deep= (drop 10 []) []) "drop 2")
(assert (deep= (drop 0 [1 2 3 4 5]) [1 2 3 4 5]) "drop 3")
(assert (deep= (drop 10 [1 2 3]) []) "drop 4")
(assert (deep= (drop -2 [:a :b :c]) [:a :b :c]) "drop 5")
(assert-error :invalid-type (drop 3 {}) "drop 6")
(assert (deep= (drop -1 [1 2 3]) [1 2]) "drop 5")
(assert (deep= (drop -10 [1 2 3]) []) "drop 6")
(assert (deep= (drop 1 "abc") "bc") "drop 7")
(assert (deep= (drop 10 "abc") "") "drop 8")
(assert (deep= (drop -1 "abc") "ab") "drop 9")
(assert (deep= (drop -10 "abc") "") "drop 10")
(assert-error :invalid-type (drop 3 {}) "drop 11")

# drop-until

Expand Down

0 comments on commit 54b54f8

Please sign in to comment.