๐พObject extension
JS โฉ object โฉ built-in โฉ Object โฉ extension
obj.mergeWith() - copy (own enumerable) properties from other sources.
replit โฉ Object_ext.js
// โญ๏ธ Global Functions
// check if value is object
function isObject(value) { return value === Object(value) }
// check if value is primitive
function isPrimitive(value) { return !isObject(value) }
// โญ๏ธ extending Object.prototype
// -------------------------------------
// method/accessor parameters
// -------------------------------------
// ๐น .defineProperty (prop, desc)
// ๐น .defineProperties (desc)
// ๐น .propertyDescriptor (prop)
// ๐น .assign (...sources)
// ๐น .mergeWith (...sources)
// ๐ธ .prototype
// ๐ธ .keys
// ๐ธ .symbols
Object.defineProperties(Object.prototype, {
// ๐น obj.defineProperty(prop, desc)
defineProperty: {
value: function(prop, descr) {
return Object.defineProperty(this, prop, descr);
},
},
// ๐น obj.defineProperties(desc)
defineProperties: {
value: function(descr) {
return Object.defineProperties(this, descr);
},
},
// ๐น obj.propertyDescriptor(prop)
propertyDescriptor: {
value: function(prop) {
return Object.getOwnPropertyDescriptor(this, prop);
},
},
// ๐น obj.assign(...sources)
assign: {
value: function(...sources) {
return Object.assign(this, ...sources);
},
},
// ๐น obj.mergeWith(...sources)
mergeWith: {
value: function(...sources) {
// prepare to collect descriptors
const descriptors = {};
// collect all descriptors from sources
sources.forEach(source => {
// own enumerable (string-keyed) properties -> descriptors
source.keys.forEach(key => {
descriptors[key] = source.propertyDescriptor(key);
});
// own enumerable (symbol-keyed) properties -> descriptors
source.symbols.forEach(sym => {
const desc = source.propertyDescriptor(sym);
if (desc.enumerable) descriptors[sym] = desc;
});
});
// merge and return
return this.defineProperties(descriptors);
},
},
// ๐ธ obj.prototype
prototype: {
get: function() {
return Object.getPrototypeOf(this);
},
},
// ๐ธ obj.keys (own enumerable)
keys: {
get: function() {
return Object.keys(this);
},
},
// ๐ธ obj.symbols (own enumerable/non-enumerable)
symbols: {
get: function() {
return Object.getOwnPropertySymbols(this);
},
},
});
// export
module.exports = {
isObject,
isPrimitive,
};
property attribute(s) of an object
Last updated