I'd like to dynamically pass parameterized processing functions as callbacks to a selective traversing function (process_matching_and_others).
In the example below, that's based on this excellent answer to a different question, I statically define the callback functions.This works, but has some disadvantages.
Apart from lacking encapsulation in general, my concern is, that I can't move the generic traversing function (process_matching_and_others) to a library.
I understood that jq doesn't support lambdas in the way, other programming languages do.
Is there any elegant and compact way to achieve the goal of dynamically define callbacks when invoking the traversal function?
Here my current code and how I verify it:
$ yq -y -f demo.jq input.yaml > actual.yaml \&& diff expected.yaml actual.yaml \&& echo "SUCCESS" || echo "FAILURE"# demo.jqdef callback_1(node): if node | has("x") then node.x = "changed" else . end;def callback_2(node): if node | has("y") then del(node.y) else . end;# This function invokes one callback for objects that are children of path_list and another callback for objects that aren't. # The current approach works as long as the callbacks are defined before the traverse function is defined. # I'd rather like to leave it to the caller of the traverse-function to decide how to process nodes that match the path and how to process others.def traverse_and_invoke_callbacks(path_list): reduce paths(objects) as $p (.; if $p[:path_list | length] == path_list then callback_1(getpath($p)) else callback_2(getpath($p)) end);traverse_and_invoke_callbacks( ["deep","path","matching"])# input.yamldeep: path: matching: m: x: change it y: don't touch n: nn: x: change it y: don't touch other_a: a: x: don't touch y: delete it other_b: b: bb: x: don't touch y: delete it other_list: - a - b - canother_other: - a: x: don't touch y: delete it - a: x: don't touch y: delete it# expected.yamldeep: path: matching: m: x: changed y: don't touch n: nn: x: changed y: don't touch other_a: a: x: don't touch other_b: b: bb: x: don't touch other_list: - a - b - canother_other: - a: x: don't touch - a: x: don't touchSUCCESS