Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@hapi/hoek/lib/applyToDefaults.js
1126 views
1
'use strict';
2
3
const Assert = require('./assert');
4
const Clone = require('./clone');
5
const Merge = require('./merge');
6
const Reach = require('./reach');
7
8
9
const internals = {};
10
11
12
module.exports = function (defaults, source, options = {}) {
13
14
Assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
15
Assert(!source || source === true || typeof source === 'object', 'Invalid source value: must be true, falsy or an object');
16
Assert(typeof options === 'object', 'Invalid options: must be an object');
17
18
if (!source) { // If no source, return null
19
return null;
20
}
21
22
if (options.shallow) {
23
return internals.applyToDefaultsWithShallow(defaults, source, options);
24
}
25
26
const copy = Clone(defaults);
27
28
if (source === true) { // If source is set to true, use defaults
29
return copy;
30
}
31
32
const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false;
33
return Merge(copy, source, { nullOverride, mergeArrays: false });
34
};
35
36
37
internals.applyToDefaultsWithShallow = function (defaults, source, options) {
38
39
const keys = options.shallow;
40
Assert(Array.isArray(keys), 'Invalid keys');
41
42
const seen = new Map();
43
const merge = source === true ? null : new Set();
44
45
for (let key of keys) {
46
key = Array.isArray(key) ? key : key.split('.'); // Pre-split optimization
47
48
const ref = Reach(defaults, key);
49
if (ref &&
50
typeof ref === 'object') {
51
52
seen.set(ref, merge && Reach(source, key) || ref);
53
}
54
else if (merge) {
55
merge.add(key);
56
}
57
}
58
59
const copy = Clone(defaults, {}, seen);
60
61
if (!merge) {
62
return copy;
63
}
64
65
for (const key of merge) {
66
internals.reachCopy(copy, source, key);
67
}
68
69
const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false;
70
return Merge(copy, source, { nullOverride, mergeArrays: false });
71
};
72
73
74
internals.reachCopy = function (dst, src, path) {
75
76
for (const segment of path) {
77
if (!(segment in src)) {
78
return;
79
}
80
81
const val = src[segment];
82
83
if (typeof val !== 'object' || val === null) {
84
return;
85
}
86
87
src = val;
88
}
89
90
const value = src;
91
let ref = dst;
92
for (let i = 0; i < path.length - 1; ++i) {
93
const segment = path[i];
94
if (typeof ref[segment] !== 'object') {
95
ref[segment] = {};
96
}
97
98
ref = ref[segment];
99
}
100
101
ref[path[path.length - 1]] = value;
102
};
103
104