1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 19:19:53 +00:00

Merge pull request #1114 from ianthehenry/drop-from-end

drop with a negative count now drops from the end
This commit is contained in:
Calvin Rose 2023-04-24 09:16:10 -05:00 committed by GitHub
commit 4ed3f2c662
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 8 deletions

View File

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

View File

@ -83,8 +83,13 @@
(assert (deep= (drop 10 []) []) "drop 2") (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 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 10 [1 2 3]) []) "drop 4")
(assert (deep= (drop -2 [:a :b :c]) [:a :b :c]) "drop 5") (assert (deep= (drop -1 [1 2 3]) [1 2]) "drop 5")
(assert-error :invalid-type (drop 3 {}) "drop 6") (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 # drop-until