Last active
November 15, 2018 07:29
-
-
Save ilyash-b/47177ed4da5caded67d793f28c5fbab4 to your computer and use it in GitHub Desktop.
find key at any level of a tree and collect the associated value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# By zzamboni | |
fn find-key [tree key]{ | |
if (eq (kind-of $tree) map) { | |
keys $tree | each [k]{ | |
if (eq $k $key) { | |
put $tree[$k] | |
} else { | |
find-key $tree[$k] | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ngs | |
data = { | |
'top-level': { | |
'xyz': | |
{ | |
'k1': 'v1', 'k2': 'v2', | |
'attrs': | |
{'xyz-ak1': 'xyz-av1', 'xyz-ak2': 'xyz-av2'} | |
} | |
'attrs': | |
{'ak1': 'av1', 'ak2': 'av2'} | |
} | |
} | |
F find_key1(tree, key) { | |
collector { | |
F kern(tree) { | |
tree is not Hash returns | |
tree.eachk(F(k) { | |
if k == key { | |
collect(tree[k]) | |
} else { | |
kern(tree[k]) | |
} | |
}) | |
} | |
kern(tree) | |
} | |
} | |
F find_key2(tree, key) { | |
collector { | |
F kern(tree) nop | |
F kern(tree:Hash) { | |
if key in tree { | |
collect(tree[key]) | |
} | |
tree.without(key).eachv(kern) | |
} | |
kern(tree) | |
} | |
} | |
F find_key3(tree, key) { | |
collector { | |
F kern(tree) nop | |
F kern(tree:Hash) { | |
tree.Box(key).each(collect) | |
tree.without(key).eachv(kern) | |
} | |
kern(tree) | |
} | |
} | |
F find_key4(tree, key, cb) { | |
tree is not Hash returns | |
tree.Box(key).each(cb) | |
tree.without(key).eachv(find_key4(X, key, cb)) | |
} | |
F find_key4(tree, key) collector find_key4(tree, key, collect) | |
echo(find_key4(data, 'attrs')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment