All Projects โ†’ caiogondim โ†’ safe-chain.js

caiogondim / safe-chain.js

Licence: other
๐Ÿ”— No more crazy checks to safely get a nested value inside an object

Programming Languages

javascript
184084 projects - #8 most used programming language

safe-chain

Travis CI Codecov

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


caiogondim.com  ยท  GitHub @caiogondim  ยท  Twitter @caio_gondim

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].