In my country (Brazil) we have a saying, who doesn't have a dog hunting with a cat.
I've been working on a project where we could not update the latest version of the node and there was no possibility to put the babel
or even the experimental flag --harmony
, because we had some enterprise restrictions to do something like that.
So it's time to use creativity ✨
const optionalChainingByPath = (object, path) => {
const pathSplitted = path.split('.')
const [firstKey] = pathSplitted
if (object[firstKey] == null || object[firstKey] ==='' ) { return null }
if (typeof object[firstKey] === 'object') {
pathSplitted.shift()
return optionalChainningByPath(object[firstKey], pathSplitted.join('.'))
}
return object[firstKey]
}
Usage:
const makeResponse = patient => ({
name: optionalChainingByPath(patient, 'personalInformation.name'),
gender: optionalChainingByPath(patient, 'personalInformation.gender'),
cardNumber: optionalChainingByPath(patient, 'personalInformation.cardNumber')
})
It's ok but unamused 😒
Let's make this cool enough 🥳
We'll use partial functions to transform this boring function into a fancy function ✨
const optionalChainingByPath = object => path => {
const pathSplitted = path.split('.')
const [firstKey] = pathSplitted
if (object[firstKey] == null || object[firstKey] === '') {
return null
}
if (typeof object[firstKey] === 'object') {
pathSplitted.shift()
return optionalChainingByPath(object[firstKey], pathSplitted.join('.'))
}
return object[firstKey]
}
Usage:
const makeResponse = patient => {
return {
name: optionalChaining('personalInformation.name'),
gender: optionalChaining('personalInformation.gender'),
cardNumber: optionalChaining('personalInformation.cardNumber')
}
}
Does sounds like a charm or doesn't?