Have opinions about JavaScript? We want to hear them. Take the 2018 JavaScript Ecosystem Survey »

guardy

0.0.7 • Public • Published

portfolio_view

CircleCI Coverage Status BCH compliance License: MIT dependencies Status

NPM

Simple and natural nested property accessor.
Protect yourself from "Cannot read property 'x' of undefined" runtime exception.

Installing

Package is available in npm. It's in umd format so it will work correctly with all popular bundlers(webpack) and also nodejs.

npm install guardy --save

Using yarn

yarn add guardy --save

For direct usage without bundler, use iife format and import file directly:

<script src="dist/guardy-iife.min.js"></script>

Usage

Wrap object with guardy and then access with no stress any property at any nested level. If not defined it will fallback to empty object {} instead of throwing "Cannot read property 'x' of undefined" runtime exception.

import { guardy } from "guardy";
 
var nestedProp = guardy(myObj).I.can.safely.access.any.property;

With defined fallback value

import { guardyFb } from "guardy";
 
var nestedProp = guardyFb(myObj, "myFallBackStringOrAnyType").I.can.safely.access.any.property.__value__;

Guardy can be successfully used together with redux when trying to access not yet initialized state properties by providing safe fallback values.

const mapStateToProps = ({ NestedReducerState }) => (
    {
       var nestedStateObject = guardy(NestedReducerState).a.nested.object;
       var nestedStateString = guardyWithFallback(NestedReducerState, "defaultString").a.nested.string.__value__;
 
       return {
           nestedStateObject,
           nestedStateString
       }
    }
);

Compatibility

Licensing

The code in this project is licensed under MIT license.

install

npm i guardy

Downloadsweekly downloads

40

version

0.0.7

license

MIT

last publish

collaborators

  • avatar
Report a vulnerability