Unverified Commit 0f880eb3 authored by Silvan Mosberger's avatar Silvan Mosberger Committed by GitHub
Browse files

`lib.dropEnd` (#370558)

parents 0b4b1319 782a0e65
Loading
Loading
Loading
Loading
+3 −2
Original line number Diff line number Diff line
@@ -94,8 +94,9 @@ let
    inherit (self.lists) singleton forEach map foldr fold foldl foldl' imap0 imap1
      filter ifilter0 concatMap flatten remove findSingle findFirst any all count
      optional optionals toList range replicate partition zipListsWith zipLists
      reverseList listDfs toposort sort sortOn naturalSort compareLists take
      drop sublist last init crossLists unique allUnique intersectLists
      reverseList listDfs toposort sort sortOn naturalSort compareLists
      take drop dropEnd sublist last init
      crossLists unique allUnique intersectLists
      subtractLists mutuallyExclusive groupBy groupBy' concatLists genList
      length head tail elem elemAt isList;
    inherit (self.strings) concatStrings concatMapStrings concatImapStrings
+41 −0
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@ let
  inherit (lib.strings) toInt;
  inherit (lib.trivial) compare min id warn pipe;
  inherit (lib.attrsets) mapAttrs;
  inherit (lib) max;
in
rec {

@@ -1497,6 +1498,46 @@ rec {
    count:
    list: sublist count (length list) list;

  /**
    Remove the last (at most) N elements of a list.


    # Inputs

    `count`

    : Number of elements to drop

    `list`

    : Input list

    # Type

    ```
    dropEnd :: Int -> [a] -> [a]
    ```

    # Examples

    :::{.example}
    ## `lib.lists.dropEnd` usage example

    ```nix
      dropEnd 2 [ "a" "b" "c" "d" ]
      => [ "a" "b" ]
      dropEnd 2 [ ]
      => [ ]
    ```
    :::

   */
  dropEnd =
    n: xs:
      take
        (max 0 (length xs - n))
        xs;

  /**
    Whether the first list is a prefix of the second list.

+24 −0
Original line number Diff line number Diff line
@@ -854,6 +854,30 @@ runTests {
    ([ 1 2 3 ] == (take 4 [  1 2 3 ]))
  ];

  testDrop = let inherit (lib) drop; in testAllTrue [
    # list index -1 is out of bounds
    # ([ 1 2 3 ] == (drop (-1) [  1 2 3 ]))
    (drop 0 [ 1 2 3 ] == [ 1 2 3 ])
    (drop 1 [ 1 2 3 ] == [ 2 3 ])
    (drop 2 [ 1 2 3 ] == [ 3 ])
    (drop 3 [ 1 2 3 ] == [ ])
    (drop 4 [ 1 2 3 ] == [ ])
    (drop 0 [ ] == [ ])
    (drop 1 [ ] == [ ])
  ];

  testDropEnd = let inherit (lib) dropEnd; in testAllTrue [
    (dropEnd 0 [ 1 2 3 ] == [ 1 2 3 ])
    (dropEnd 1 [ 1 2 3 ] == [ 1 2 ])
    (dropEnd 2 [ 1 2 3 ] == [ 1 ])
    (dropEnd 3 [ 1 2 3 ] == [ ])
    (dropEnd 4 [ 1 2 3 ] == [ ])
    (dropEnd 0 [ ] == [ ])
    (dropEnd 1 [ ] == [ ])
    (dropEnd (-1) [ 1 2 3 ] == [ 1 2 3 ])
    (dropEnd (-1) [ ] == [ ])
  ];

  testListHasPrefixExample1 = {
    expr = lists.hasPrefix [ 1 2 ] [ 1 2 3 4 ];
    expected = true;