DEV Community

Discussion on: Optional handmade chaining 🤓

Collapse
 
felipperegazio profile image
Felippe Regazio • Edited

Really cool solution, it does look like a charm : )
You can also extract the object value in a functional style with:

const optionalChaining = (obj, str) => (obj && str) && (() => str.split('.').reduce((o, i) => o[i], obj))();
Enter fullscreen mode Exit fullscreen mode

and use like that:

const letters = { a: { b: 'c' } };

optionalChaining(letters, 'a'); // {b: "c"}
optionalChaining(letters, 'a.b'); // 'c'
optionalChaining(letters, 'a.b.e'); // undefined
optionalChaining(letters, 'z'); // undefined
Enter fullscreen mode Exit fullscreen mode

We can also extend the Object prototype to avoid some problems (dont know about how good or bad it could be in terms of design, but its possible):

Object.prototype.optionalChaining = function (str) {
  return str.split('.').reduce((o, i) => o[i], this);
}

const letters = { a: { b: 'c' } };

letters.optionalChaining('a'); // {b: "c"}
letters.optionalChaining('a.b'); // 'c'
letters.optionalChaining('a.b.e'); // undefined
letters.optionalChaining('z'); // undefined
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wakeupmh profile image
Marcos Henrique

Clean and beauty, thanks bro