lib: implement filterAttrs'

Uhh... I forgot that this is a thing.
This commit is contained in:
Gabriel Arazas 2024-08-08 11:19:03 +08:00
parent ebece66e15
commit 632e1b1d8c
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
2 changed files with 24 additions and 3 deletions

View File

@ -14,11 +14,20 @@
lib.count (attr: pred attr.name attr.value)
(lib.mapAttrsToList lib.nameValuePair attrs);
/* Filters and groups the attribute set into two separate attribute.
/* Filters and groups the attribute set into two separate attribute where it
either accepted or denied from a given predicate function.
Example:
filterAttrs' (n: v: v == 4) { a = 4; b = 2; c = 6; }
=> { ok = { a = 4; }; reject = { b = 2; c = 6; }; }
=> { ok = { a = 4; }; notOk = { b = 2; c = 6; }; }
*/
filterAttrs' = f: attrs: { };
filterAttrs' = f: attrs:
lib.foldlAttrs (acc: name: value: let
isOk = f name value;
in {
ok = acc.ok // lib.optionalAttrs isOk { ${name} = value; };
notOk = acc.notOk // lib.optionalAttrs (!isOk) { ${name} = value; };
})
{ ok = { }; notOk = { }; }
attrs;
}

View File

@ -12,4 +12,16 @@ lib.runTests {
};
expected = 2;
};
testFilterAttrs' = {
expr = self.trivial.filterAttrs' (n: v: v == 4) {
e = 5;
f = 7;
a = 4;
};
expected = {
ok = { a = 4; };
notOk = { e = 5; f = 7; };
};
};
}