In one of the node examples , I came across below line
const extend = require('util')._extend;
Can anyone explain whats the purpose of _extend method of 'util' node module ?
Low-frills deep copy:
var obj2 = JSON.parse(JSON.stringify(obj1));
For a shallow copy, use Node's built-in util._extend() function.
var extend = require('util')._extend;
var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5
Source code of Node's _extend function is in here: https://github.com/joyent/node/blob/master/lib/util.js
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
For more information you can follow EXTEND
Hope this helps you.
In addition to Shallow copy as mentioned by Nitin above, it also combines the properties of the parameters passed
From the source code of util._extend
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
So it combines the properties of origin
and add
parameters from the above code snippet and returns the extended object.