forked from wilmoore/selectn.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
37 lines (32 loc) · 1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use strict'
import curry2 from 'curry2';
import dotted from 'brackets2dots';
import splits from 'dotsplit.js';
var string = Object.prototype.toString
export default curry2(selectn);
/**
* Curried property accessor function that resolves deeply-nested object properties via dot/bracket-notation
* string path while mitigating `TypeErrors` via friendly and composable API.
*
* @param {String|Array} path
* Dot/bracket-notation string path or array.
*
* @param {Object} object
* Object to access.
*
* @return {Function|*|undefined}
* (1) returns `selectn/1` when partially applied.
* (2) returns value at path if path exists.
* (3) returns undefined if path does not exist.
*/
function selectn (path, object) {
var idx = -1
var seg = string.call(path) === '[object Array]' ? path : splits(dotted(path))
var end = seg.length
var ref = end ? object : void 0
while (++idx < end) {
if (Object(ref) !== ref) return void 0
ref = ref[seg[idx]]
}
return typeof ref === 'function' ? ref() : ref
}