Groovy web console

subscribe to the feed Subscribe
to this
site
PathUtils (via #groovywebconsole)
tweet this snippet Tweet
this
script

PathUtils

Published 1 month ago by Luis Epifanio with tags Path safe navigation on path structures
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
Object valueOnPath(def target, String path  ) {
    if([target, path].any{ !it }){
        return null
    }
        
    return path.tokenize('.').inject(target) { v, k ->
        if(!v){return null}
        v."$k" ?: null
        } 
}

boolean checkPathOn(def target, String path  ) {
  valueOnPath(target, path) as Boolean
}

def whatever = [
    path: [
        to:[
            value: 42,
            hell: 'Is fun'
        ]
    ]
]

assert false == checkPathOn(null, null)
assert false == checkPathOn(whatever, null)
assert false == checkPathOn(whatever,'')

assert null == valueOnPath(null, null)
assert null == valueOnPath(whatever, null)
assert null == valueOnPath(whatever,'')

assert true == checkPathOn(whatever, 'path.to.value')
assert 42 == valueOnPath(whatever, 'path.to.value')

assert true == checkPathOn(whatever, 'path.to.hell')
assert 'Is fun' == valueOnPath(whatever, 'path.to.hell')

assert false == checkPathOn(whatever, 'this.path.not.even.exists')
assert null == valueOnPath(whatever, 'this.path.not.even.exists')