try.js
v0.1.1
Published
JavaScript equivalent of Rails try method
Downloads
7
Readme
try.js
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
Alternatives
MIT © @fernahh