diff options
| author | Johannes Kirschbauer <hsjobeki@gmail.com> | 2025-04-23 14:20:47 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-04-23 14:20:47 +0200 |
| commit | be393db73eea64d4e3ae17c89e8e7005f87f9c74 (patch) | |
| tree | 4010b0204f5162081893081749e11cdef154ed3e /lib | |
| parent | goarista: init at 0-unstable-2025-03-24 (#396427) (diff) | |
| parent | lib.takeEnd: init (diff) | |
| download | nixpkgs-be393db73eea64d4e3ae17c89e8e7005f87f9c74.tar.gz | |
lib.takeEnd: init (#398222)
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/default.nix | 1 | ||||
| -rw-r--r-- | lib/lists.nix | 34 | ||||
| -rw-r--r-- | lib/tests/misc.nix | 63 |
3 files changed, 98 insertions, 0 deletions
diff --git a/lib/default.nix b/lib/default.nix index c433ca6a3e09..e6e6aaa983d5 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 aa587f52c4ac..ef2d74b63162 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -1357,6 +1357,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; |
