safe-reaper
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

safe-reaper

NPM version Build Status Coverage Status code style: prettier

Retrieve property value by specifying an expression but without any null/undefined reference concern

Install

npm

npm install --save safe-reaper

bower

bower install --save safe-reaper

Import

ES2015

import { reap } from 'safe-reaper'

CommonJS

const { reap } = require('safe-reaper')

script

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>DEMO</title>
  </head>
  <body>
    <script type="text/javascript" src="node_modules/safe-reaper/dist/safereaper.js"></script> 
    <script type="text/javascript">
      var reap = window.reap
    </script> 
  </body>
</html>

Usage

reap(null, 'user.age') // undefined
reap(null, 'user.age', 38) // 38
 
const obj = {
  user: {
    name: 'HanMeimei'
  }
}
 
reap<string>(obj, 'user.name') // Hanmeimei
reap<undefined>(obj, 'user.age') // undefined
reap<number>(obj, 'user.age', 33) // 33
reap<any>(obj, null, 33) // Error occurs
reap<string, string>(obj, 'user.name', '', val => `Hello ${val}`) // Hello HanMeimei
 
const users = [
  {
    name: 'LiLei'
  }
]
 
reap<string>(users, '[0].name') // LiLei
reap<string>(users, '[0]["name"]') // LiLei
reap<number>(users, '[0]["age"]', 99) // 99

reap(source, pathExpression[, defaultValue, extraHandler])

  • source: object you are going to use
  • pathExpression: the path leads to the result in specifying source
  • defaultValue: will be used if source is null/undefined, or any intermediate value evaluated in pathExpression
  • extraHandler: a function will be called to evaluate the final return

accept-expression

Dot notation - a, a.b, a.b.c

Bracket notation - a['b'], a[0], a[0].c, a[0]['c']

Hybrid - a.b[0], a[0].b

LICENSE

GPL v3 License

Readme

Keywords

Package Sidebar

Install

npm i safe-reaper

Weekly Downloads

0

Version

2.1.0

License

GPL-3.0

Unpacked Size

43.7 kB

Total Files

8

Last publish

Collaborators

  • howard.zuo