safe-chain
v3.0.5
Published
No more crazy checks to safely get a nested value inside an object
Downloads
38
Readme
safe-chain
No more crazy checks to safely get a nested value inside an object.
Think of it as Ruby safe operator or CoffeeScript existential operator, implemented as a simple function in JavaScript.
Installation
npm install safe-chain
Usage
Nested value
// Before
const nestedVal = (
obj &&
obj.lorem &&
obj.lorem.ipsum &&
obj.lorem.ipsum.dolor
)
// After
const nestedVal = safeChain(obj, `lorem.ipsum.dolor`)
Nested function
// Before
const nestedFuncVal = (
obj &&
obj.lorem &&
obj.lorem.ipsum &&
obj.lorem.ipsum.dolor &&
typeof obj.lorem.ipsum.dolor === 'function'
? obj.lorem.ipsum.dolor()
: undefined
)
// After
const nestedFuncVal = safeChain(obj, `lorem.ipsum.dolor`)()
Credits
- Ruby safe operator
- CoffeeScript existential operator
- Icon by Martin Chapman Fromm from the Noun Project
caiogondim.com · GitHub @caiogondim · Twitter @caio_gondim