safe-chain

v3.0.5
No more crazy checks to safely get a nested value inside an object

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

npm i safe-chain

Metadata

  • MIT
  • Whatever
  • Caio Gondim
  • released 3/13/2018

Downloads

Maintainers