Skip to content

Instantly share code, notes, and snippets.

@marcolz
Last active July 19, 2016 00:30
Show Gist options
  • Save marcolz/5b6005b8333324710beaea35dfa27bdf to your computer and use it in GitHub Desktop.
Save marcolz/5b6005b8333324710beaea35dfa27bdf to your computer and use it in GitHub Desktop.
My ES6 implementation of Rails' style #try()
// Traverse an object and attempt to extract the value(s) of one
// or more properties, without worrying about non-Object values.
const maybe = (obj, traverse, fields) => {
if (!(fields instanceof Array)) {
fields = [fields]
}
let result
try {
const leaf = traverse.reduce((memo, prop) => memo[prop], obj)
result = fields.reduce((memo, field) => {
leaf[field].wuut
return { ...memo, [field]: leaf[field] }
}, {})
} catch(e) {}
return result
}
// Example:
// const foo = { ciao: { what: 'Pizza', where: 'Pisa' } }
//
// maybe(foo, ['ciao'], 'what') -> { what: 'Pizza' }
// maybe(foo, ['ciao'. 'bello'], 'what') -> undefined
// maybe(foo, ['ciao'. 'bello'], ['what', 'where']) -> { what: 'Pizza', where: 'Pisa' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment