npm.io
3.0.5 • Published 8 years ago

safe-chain

Licence
MIT
Version
3.0.5
Deps
0
Size
43 kB
Vulns
0
Weekly
0

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