perfget
Fastest method for returning deeply nested properties based on a string path.
If you merely try to access a path like a.b.c
and either a
or a.b
does not exist,
you will throw an error. If a
is not defined: ReferenceError: a is not defined
.
If a.b
is not defined: TypeError: Cannot read property 'c' of undefined
.
The only safe pattern for property access is: a && a.b && a.b.c
. Relying on this
pattern leads to verbose, error-prone code. You will also have problems passing
this around to other functions.
get
will allow you to pass get( "a.b.c" )
as a path or as an array of "segments",
get( ["a", "b", "c"] )
. If any part of the path fails, get
returns undefined
.
Any properties you can normally access, get
can return. For instance, this will work
in the browser: get( "document.body.childNodes.length" );
Notes
No, this does not use try/catch
. That tends to slow things down, especially in the
browser. For each "depth", perfget constructs a function capable of accessing
properties at that depth. The function gets cached for reuse. Splitting long strings
can also take time, so we cache those as well for reliable, fast results.
Getting started
Download and include perfget.min.js
on a browser page or install via npm:
npm install perfget --save-dev
API
get( path:String|Array )
: Returns property values ofthis
._get( receiver:Object )
: Returns a function which takes a path (just likeget
).get_( path:String|Array )
: Returns a function which takes a receiver.
Uses:
Use get()
globally
<!-- Browser example -->
// NodeJS examplevar get = get;; //'node'
Use get()
for your custom objects
<!-- Browser method example -->
<!-- Browser Object.create example -->
// NodeJS method examplevar perfget = ; { thisstuff = thangs: thangs ;}Klassprototypeget = perfgetget; var k = 123 ;k; //2
// NodeJS util.inherits examplevar perfget = ;var util = ; { thisstuff = thangs: thangs ;}util; var k = 123 ;k; //2
// NodeJS Object.create examplevar perfget = ;var obj = Object;objstuff = thangs: 123; obj; //2
Use _get()
to wrap objects
<!-- Browser example -->
// NodeJS examplevar _get = _get;var global = ;global "process.versions.v8" ;
Use get_()
with promises
<!-- Browser example -->
// NodeJS examplevar Promise = Promise;var http = ;var get_ = get_;var getResults = ; { return { var req = https; req; if body req; req; } ;} { var body = ""; return { res; res; } ;} { return JSON;} ;
Use get_()
functionally, like with .map()
<!-- Browser example -->
// NodeJS examplevar get_ = get_;var pluckId = ;var obj = deeply:nested:id:1obj; // [1]
Change log
Date | Version | Notes |
---|---|---|
2014-03-24 | v0.2.1 | Added better support for Object.create |
2014-03-22 | v0.2.0 | Added support for util.inherits |
2014-03-18 | v0.1.1 | Replaced gulp-mocha with gulp-nodeunit, added travis-ci integration |