Last active
July 19, 2016 00:30
-
-
Save marcolz/5b6005b8333324710beaea35dfa27bdf to your computer and use it in GitHub Desktop.
My ES6 implementation of Rails' style #try()
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
// 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