0.1.1 • Published 7 years ago

try.js v0.1.1

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

try.js

Build status XO code style

JavaScript equivalent of Rails try() method

Why?

When we want get a value of a determined path, sometimes some property is undefined, and this break the execution flux. This function returns undefined when a path is invalid. Read more.

Usage

Simple example:

// without try.js
const obj = {}

obj.x.y // TypeError: Cannot read property 'y' of undefined

// to fix
const obj = {}

if (obj && obj.x && obj.x.y)
  return obj.x.y // undefined

// with try.js
const obj = {}

tryjs(obj, 'y.x') // undefined

With function:

// without try.js
const obj = {
  sayHello: () => 'Hello'
}

if (obj && (typeof obj.sayHello === 'function')
  return obj.sayHello() // 'Hello'

// with try.js
const obj = {
  sayHello: () => 'Hello'
}

tryjs(obj, 'sayHello') // 'Hello'

Function with params:

const obj = {
  add: (x, y) => x + y
}

tryjs(obj, 'add', [1, 2]) // 3

Install

npm install try.js

Or download the dist file.

Alternatives

MIT © @fernahh