summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorazahi <azat@bahawi.net>2025-04-13 00:38:41 +0300
committerazahi <azat@bahawi.net>2025-04-13 17:37:35 +0300
commit9fee9e737163b093afd46661d125e559863f6286 (patch)
tree4a65f25b1d5331d15008e4a8c9990109e2c09bc6 /lib
parentpython313Packages.cramjam: fix eval (#398382) (diff)
downloadnixpkgs-9fee9e737163b093afd46661d125e559863f6286.tar.gz
lib.takeEnd: init
Diffstat (limited to 'lib')
-rw-r--r--lib/default.nix1
-rw-r--r--lib/lists.nix34
-rw-r--r--lib/tests/misc.nix63
3 files changed, 98 insertions, 0 deletions
diff --git a/lib/default.nix b/lib/default.nix
index 19316addb8cb..eeed3d8e3f42 100644
--- a/lib/default.nix
+++ b/lib/default.nix
@@ -279,6 +279,7 @@ let
naturalSort
compareLists
take
+ takeEnd
drop
dropEnd
sublist
diff --git a/lib/lists.nix b/lib/lists.nix
index e119606dd5e7..ec0fe22d2afa 100644
--- a/lib/lists.nix
+++ b/lib/lists.nix
@@ -1463,6 +1463,40 @@ rec {
take = count: sublist 0 count;
/**
+ Return the last (at most) N elements of a list.
+
+ # Inputs
+
+ `count`
+
+ : Maximum number of elements to pick
+
+ `list`
+
+ : Input list
+
+ # Type
+
+ ```
+ takeEnd :: int -> [a] -> [a]
+ ```
+
+ # Examples
+ :::{.example}
+ ## `lib.lists.takeEnd` usage example
+
+ ```nix
+ takeEnd 2 [ "a" "b" "c" "d" ]
+ => [ "c" "d" ]
+ takeEnd 2 [ ]
+ => [ ]
+ ```
+
+ :::
+ */
+ takeEnd = n: xs: drop (max 0 (length xs - n)) xs;
+
+ /**
Remove the first (at most) N elements of a list.
# Inputs
diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix
index d17231061d69..5b86e92c5750 100644
--- a/lib/tests/misc.nix
+++ b/lib/tests/misc.nix
@@ -1262,6 +1262,69 @@ runTests {
)
];
+ testTakeEnd =
+ let
+ inherit (lib) takeEnd;
+ in
+ testAllTrue [
+ (
+ takeEnd 0 [
+ 1
+ 2
+ 3
+ ] == [ ]
+ )
+ (
+ takeEnd 1 [
+ 1
+ 2
+ 3
+ ] == [ 3 ]
+ )
+ (
+ takeEnd 2 [
+ 1
+ 2
+ 3
+ ] == [
+ 2
+ 3
+ ]
+ )
+ (
+ takeEnd 3 [
+ 1
+ 2
+ 3
+ ] == [
+ 1
+ 2
+ 3
+ ]
+ )
+ (
+ takeEnd 4 [
+ 1
+ 2
+ 3
+ ] == [
+ 1
+ 2
+ 3
+ ]
+ )
+ (takeEnd 0 [ ] == [ ])
+ (takeEnd 1 [ ] == [ ])
+ (
+ takeEnd (-1) [
+ 1
+ 2
+ 3
+ ] == [ ]
+ )
+ (takeEnd (-1) [ ] == [ ])
+ ];
+
testDrop =
let
inherit (lib) drop;