Optional handmade chaining 🤓

Marcos Henrique - Jan 4 '21 - - Dev Community

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]
}

Enter fullscreen mode Exit fullscreen mode

Usage:

const makeResponse = patient => ({
  name: optionalChainingByPath(patient, 'personalInformation.name'),
  gender: optionalChainingByPath(patient, 'personalInformation.gender'),
  cardNumber: optionalChainingByPath(patient, 'personalInformation.cardNumber')
})
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

Usage:

const makeResponse = patient => {
  return {
    name: optionalChaining('personalInformation.name'),
    gender: optionalChaining('personalInformation.gender'),
    cardNumber: optionalChaining('personalInformation.cardNumber')
  }
}
Enter fullscreen mode Exit fullscreen mode

Does sounds like a charm or doesn't?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player