lib/util: add groupListBySize

Splits up a list into many sub-lists based on the given max-size.

e.g.
```nix
groupListBySize 2 [ 1 2 3 4 5 ]
=> [ [ 1 2 ] [ 3 4 ] [ 5 ] ]
```
This commit is contained in:
Matt Sturgeon 2024-08-19 00:45:47 +01:00
parent 693e749edb
commit 8f99c3953c
No known key found for this signature in database
GPG key ID: 4F91844CED1A8299
3 changed files with 61 additions and 0 deletions

View file

@ -71,6 +71,7 @@ let
concatNonEmptyLines concatNonEmptyLines
emptyTable emptyTable
enableExceptInTests enableExceptInTests
groupListBySize
hasContent hasContent
ifNonNull' ifNonNull'
listToUnkeyedAttrs listToUnkeyedAttrs

View file

@ -147,4 +147,23 @@ rec {
${string} ${string}
EOF EOF
''; '';
# Split a list into a several sub-list, each with a max-size of `size`
groupListBySize =
size: list:
reverseList (
foldl' (
lists: item:
let
first = head lists;
rest = drop 1 lists;
in
if lists == [ ] then
[ [ item ] ]
else if length first < size then
[ (first ++ [ item ]) ] ++ rest
else
[ [ item ] ] ++ lists
) [ ] list
);
} }

View file

@ -333,6 +333,47 @@ let
"MIxEd" "MIxEd"
]; ];
}; };
testGroupListBySize = {
expr = {
empty = helpers.groupListBySize 5 [ ];
"5/5" = helpers.groupListBySize 5 (lib.genList lib.id 5);
"13/5" = helpers.groupListBySize 5 (lib.genList lib.id 13);
};
expected = {
empty = [ ];
"5/5" = [
[
0
1
2
3
4
]
];
"13/5" = [
[
0
1
2
3
4
]
[
5
6
7
8
9
]
[
10
11
12
]
];
};
};
}; };
in in
if results == [ ] then if results == [ ] then