Skip to content

Instantly share code, notes, and snippets.

@mkmik
Created September 6, 2023 04:34
Show Gist options
  • Save mkmik/ba6110b5fa23352f9c9304a6aa51e614 to your computer and use it in GitHub Desktop.
Save mkmik/ba6110b5fa23352f9c9304a6aa51e614 to your computer and use it in GitHub Desktop.
// "hide" a field with a given field name or matching a given predicate.
// Optionally, change the value of the field being mapped.
//
// This is useful until jsonnet gains the ability of using "::" in object comprehension, see
// https://github.com/google/jsonnet/issues/312#issuecomment-1580533298
local hide(obj, field=null, pred=function(name) (name == field), map=function(value) value) =
std.foldl(
function(acc, f)
if pred(f.key) then
acc { [f.key]:: map(f.value) }
else
acc { [f.key]: f.value },
std.objectKeysValues(obj),
{}
);
assert std.assertEqual(
hide({ a: 1, b: 2 }, field='b'),
{ a: 1 },
);
assert std.assertEqual(
hide({ a: 1, b: 2 }, field='b').b,
2,
);
assert std.assertEqual(
hide({ a: 1, _b: 2 }, pred=function(name) std.startsWith(name, '_')),
{ a: 1 },
);
assert std.assertEqual(
hide({ a: 1, b: 2 }, field='b', map=function(_) null).b,
null,
);
hide
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment