How to use the clone function from hoek

Find comprehensive JavaScript hoek.clone code examples handpicked from public code repositorys.

hoek.clone is a utility function in the hoek module for JavaScript that creates a deep copy of an object or array.

14
15
16
17
18
19
20
21
22
internals.implementation = (server, options) => {

    Hoek.assert(options, 'Missing jwt auth strategy options');
    Hoek.assert(options.key, 'Missing required private key in configuration');

    const settings = Hoek.clone(options);

    const scheme = {
        authenticate: async (request, h) => {
fork icon2
star icon6
watch icon1

72
73
74
75
76
77
78
79
80
81
        },
        y: 'y',
        z: new Date()
    };

var copy = Hoek.clone(nestedObj);

copy.x.b = 100;

console.log(copy.y)        // results in 'y'
fork icon170
star icon1
watch icon33

How does hoek.clone work?

hoek.clone is a utility function in the hoek module for JavaScript that creates a deep copy of an object or array. When you call hoek.clone, you pass in an object or array that you want to copy. The function creates a new object or array with the same properties and values as the original, but with no shared references to the original object. hoek.clone creates a deep copy, meaning that if the original object or array contains other objects or arrays, they will also be copied recursively. This ensures that the new object or array is a complete and independent copy of the original, and any modifications made to the copy will not affect the original object. Note that hoek.clone is similar to the built-in JSON.parse(JSON.stringify(obj)) method for creating a deep copy, but hoek.clone has some additional features that make it more robust and reliable in certain situations. For example, hoek.clone can handle circular references in objects or arrays, while JSON.parse(JSON.stringify(obj)) will throw an error if it encounters a circular reference. By using hoek.clone, you can create a deep copy of an object or array that is independent of the original, allowing you to make modifications or manipulations without affecting the original object.

119
120
121
122
123
124
125
126
127
128

setUrl(url, stripTrailingSlash) {

    Hoek.assert(this.params === null, 'Cannot change request URL after routing');

    url = (typeof url === 'string' ? Url.parse(url, true) : Hoek.clone(url));

    // Apply path modifications

    let path = this._core.router.normalize(url.pathname || '');        // pathname excludes query
fork icon0
star icon1
watch icon2

+ 3 other calls in file

211
212
213
214
215
216
217
218
219
obj.__proto__ = Object.getPrototypeOf(this);

obj.isJoi = true;
obj._type = this._type;
obj._settings = internals.concatSettings(this._settings);
obj._valids = Hoek.clone(this._valids);
obj._invalids = Hoek.clone(this._invalids);
obj._tests = this._tests.slice();
obj._refs = this._refs.slice();
fork icon813
star icon0
watch icon2

+ 17 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const Hoek = require("hoek");

// Define an object that we want to copy
const originalObj = {
  name: "John",
  age: 30,
  hobbies: ["reading", "hiking", "cooking"],
};

// Use Hoek.clone to create a deep copy of the object
const clonedObj = Hoek.clone(originalObj);

// Modify the cloned object without affecting the original
clonedObj.age = 31;
clonedObj.hobbies.push("swimming");

// Log the original and cloned objects to the console
console.log("Original:", originalObj);
console.log("Cloned:", clonedObj);

In this example, we start by requiring the hoek module and defining an object called originalObj that we want to copy. We then use Hoek.clone to create a deep copy of the object and assign the copy to a new variable called clonedObj. We then modify the age and hobbies properties of clonedObj, demonstrating that the original object is not affected by the modifications. Finally, we log both the original and cloned objects to the console, showing that they have different memory addresses and contain the same properties and values. Note that Hoek.clone can also be used to copy arrays and other types of objects, in addition to plain JavaScript objects.

35
36
37
38
39
40
41
42
43
44
 * @param {Function} callback function to process result
 * @api public
 */
internals.ProcessMonitor.prototype.leaks = function (callback) {

    var loggedLeaks = Hoek.clone(this._leaks);
    this._leaks = [];

    callback(null, loggedLeaks);
};
fork icon165
star icon0
watch icon1

73
74
75
76
77
78
79
80
81
82
    }
    else {
        const trueHasDefault = Hoek.reach(trueCase, 'flags.default');
        target[childKey] = (trueHasDefault && !ignoreDefaults) ?
            trueHasDefault :
            Hoek.clone(internals.joiDictionary[trueCase.type]);
    }
}
else {
    const childHasDefault = Hoek.reach(schemaDescription.children[childKey], 'flags.default');
fork icon9
star icon0
watch icon3

+ 3 other calls in file

33
34
35
36
37
38
39
40
41
42
};


var broadcast = exports.broadcast = function (log, options, callback) {

    options = Hoek.clone(options);

    if (!log.length) {
        return callback(null);
    }
fork icon9
star icon0
watch icon2

356
357
358
359
360
361
362
363
364
    }
*/

exports.authenticate = function (res, credentials, artifacts, options) {

    artifacts = Hoek.clone(artifacts);
    options = options || {};

    if (res.headers['www-authenticate']) {
fork icon6
star icon0
watch icon2

98
99
100
101
102
103
104
105
106
107

// if its a single parameter
if (schemaObj.properties === undefined) {
  // console.log('a', JSON.stringify(schemaObj) + '\n');

  let item = Hoek.clone(schemaObj)
  item.in = parameterType
  item.name = parameterType
  item.schema = {}
  item.schema.type = item.type
fork icon0
star icon8
watch icon4

103
104
105
106
107
108
109
110
111
112
obj._settings = internals.concatSettings(this._settings);
obj._valids = Hoek.clone(this._valids);
obj._invalids = Hoek.clone(this._invalids);
obj._tests = this._tests.slice();
obj._refs = this._refs.slice();
obj._flags = Hoek.clone(this._flags);

obj._description = this._description;
obj._unit = this._unit;
obj._notes = this._notes.slice();
fork icon0
star icon2
watch icon0

+ 5 other calls in file

214
215
216
217
218
219
internals.Listener.subscription = function (path, options) {

    Hoek.assert(path, 'Subscription missing path');
    Joi.assert(options, internals.subSchema, 'Invalid subscription options: ' + path);

    const settings = Hoek.clone(options || {});
fork icon86
star icon0
watch icon2

14
15
16
17
18
19
20
21
22
if (arguments.length !== 2) {
    callback = arguments[0];
    options = {};
}

var settings = Hoek.clone(options);
settings.host = settings.host || 'pool.ntp.org';
settings.port = settings.port || 123;
settings.resolveReference = settings.resolveReference || false;
fork icon1
star icon0
watch icon18

157
158
159
160
161
162
163
164
165
166
}

const bind = request.route.settings.bind

if (settings.passThrough) {
  options.headers = Hoek.clone(request.headers)
  delete options.headers.host
  delete options.headers['content-length']

  if (settings.acceptEncoding === false) {
fork icon2
star icon11
watch icon4

93
94
95
96
97
98
99
100
101
102

var payloadSupported = (uri.method !== 'GET' && uri.method !== 'HEAD' && options.payload !== null && options.payload !== undefined);
if (payloadSupported &&
    (typeof options.payload === 'string' || Buffer.isBuffer(options.payload))) {

    uri.headers = Hoek.clone(uri.headers) || {};
    uri.headers['Content-Length'] = Buffer.isBuffer(options.payload) ? options.payload.length : Buffer.byteLength(options.payload);
}

var redirects = (options.hasOwnProperty('redirects') ? options.redirects : false);      // Needed to allow 0 as valid value when passed recursively
fork icon107
star icon0
watch icon2

204
205
206
207
208
209
210
211
212
213

    data = data();
    _generated = true;
}

const update = (internals.flag('clone', handler, event) ? Hoek.clone(data) : data);
const args = (internals.flag('spread', handler, event) && Array.isArray(update) ? update : [update]);

if (internals.flag('tags', handler, event) &&
    criteria.tags) {
fork icon25
star icon0
watch icon2

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


exports.create = function (key, options) {


    Hoek.assert(typeof key === 'string', 'Invalid reference key:', key);


    const settings = Hoek.clone(options);         // options can be reused and modified


    const ref = function (value, validationOptions) {


        return Hoek.reach(ref.isContext ? validationOptions.context : value, ref.key, settings);
fork icon0
star icon1
watch icon0

290
291
292
293
294
295
296
297
298
299

if (typeof this._object !== 'object') {
    return this.details[0].message;
}

const obj = Hoek.clone(this._object || {});

for (let i = this.details.length - 1; i >= 0; --i) {        // Reverse order to process deepest child first
    const pos = i + 1;
    const error = this.details[i];
fork icon0
star icon1
watch icon0

1234
1235
1236
1237
1238
1239
1240
1241
1242
1243

it('errors on invalid credentials (id)', function (done) {

    credentialsFunc('123456', function (err, credentials) {

        var creds = Hoek.clone(credentials);
        delete creds.id;
        var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
        expect(auth).to.not.exist();
        done();
fork icon1
star icon0
watch icon1

+ 2 other calls in file

117
118
119
120
121
122
123
124
125
126

var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
    keys = keys.concat(Object.getOwnPropertySymbols(object));
}
var keyLengths = Hoek.clone(keys);
internals.indentLevel = internals.indentLevel + 1;
var out = '{\n';

for (var i = 0, il = keys.length; i < il; ++i) {
fork icon0
star icon0
watch icon1

+ 83 other calls in file

206
207
208
209
210
211
212
213
214
215
                path: 'to get here'
            }]
        }
    }
};
var orig = Hoek.clone(obj);

var out = Purdy.stringify(obj, { plain: false, path: true, align: 'right' });
expect(out).to.equal('{\n    \u001b[1m\u001b[37mtravel\u001b[39m\u001b[22m: {\n        \u001b[34m// \u001b[39m\u001b[34mtravel.down\u001b[39m\n        \u001b[1m\u001b[37mdown\u001b[39m\u001b[22m: {\n            \u001b[34m// \u001b[39m\u001b[34mtravel.down.a\u001b[39m\n            \u001b[1m\u001b[37m  a\u001b[39m\u001b[22m: [\n                \u001b[34m// \u001b[39m\u001b[34mtravel.down.a.0\u001b[39m\n                [\u001b[1m\u001b[37m0\u001b[39m\u001b[22m] {\n                    \u001b[34m// \u001b[39m\u001b[34mtravel.down.a.0.path\u001b[39m\n                    \u001b[1m\u001b[37mpath\u001b[39m\u001b[22m: \u001b[33m\'to get here\'\u001b[39m\n                }\n            ]\n        }\n    }\n}');
expect(obj).to.deep.equal(orig);
fork icon0
star icon0
watch icon1

+ 83 other calls in file