Skip to content

AndersDJohnson/null-propagation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

null-propagation

Emulate null propagation operator.

Like Facebook's idx and Lodash's get, but even more terse than the former, and real syntax unlike the latter.

The use of real syntax enables static analysis tools.

import np from 'null-propagation'

const obj = {
  a: {
    b: 'B2'
  },
  z: []
}

For undefined values, returns undefined:

const c = np(() => obj.a.c)

With a default as a 2nd argument, returns that value:

const c2 = np(() => obj.a.c, 'C2')

For defined values, returns that value:

const b = np(() => obj.a.b)

Works with arrays, returns undefined:

const z = np(() => obj.z[0].y)

Throws other errors:

np(() => { throw new Error('some error') })