Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@hapi/hoek/lib/reach.js
1126 views
1
'use strict';
2
3
const Assert = require('./assert');
4
5
6
const internals = {};
7
8
9
module.exports = function (obj, chain, options) {
10
11
if (chain === false ||
12
chain === null ||
13
chain === undefined) {
14
15
return obj;
16
}
17
18
options = options || {};
19
if (typeof options === 'string') {
20
options = { separator: options };
21
}
22
23
const isChainArray = Array.isArray(chain);
24
25
Assert(!isChainArray || !options.separator, 'Separator option is not valid for array-based chain');
26
27
const path = isChainArray ? chain : chain.split(options.separator || '.');
28
let ref = obj;
29
for (let i = 0; i < path.length; ++i) {
30
let key = path[i];
31
const type = options.iterables && internals.iterables(ref);
32
33
if (Array.isArray(ref) ||
34
type === 'set') {
35
36
const number = Number(key);
37
if (Number.isInteger(number)) {
38
key = number < 0 ? ref.length + number : number;
39
}
40
}
41
42
if (!ref ||
43
typeof ref === 'function' && options.functions === false || // Defaults to true
44
!type && ref[key] === undefined) {
45
46
Assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain);
47
Assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
48
ref = options.default;
49
break;
50
}
51
52
if (!type) {
53
ref = ref[key];
54
}
55
else if (type === 'set') {
56
ref = [...ref][key];
57
}
58
else { // type === 'map'
59
ref = ref.get(key);
60
}
61
}
62
63
return ref;
64
};
65
66
67
internals.iterables = function (ref) {
68
69
if (ref instanceof Set) {
70
return 'set';
71
}
72
73
if (ref instanceof Map) {
74
return 'map';
75
}
76
};
77
78