Skip to content

Instantly share code, notes, and snippets.

@ilyash-b
Last active November 15, 2018 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyash-b/47177ed4da5caded67d793f28c5fbab4 to your computer and use it in GitHub Desktop.
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
# 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]
}
}
}
}
#!/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