From 9fee9e737163b093afd46661d125e559863f6286 Mon Sep 17 00:00:00 2001 From: azahi Date: Sun, 13 Apr 2025 00:38:41 +0300 Subject: [PATCH] lib.takeEnd: init --- lib/default.nix | 1 + lib/lists.nix | 34 +++++++++++++++++++++++++ lib/tests/misc.nix | 63 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) 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 @@ -1462,6 +1462,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. 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;