Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Create new object with props from both `source` and `changes` objects.
- *
- * @param {Object} source Source object.
- * @param {Object} changes Object, which props overrides source's props.
- * @param {number} [mergeThreshold=100] Maximum count of source's own props,
- * after which source object will be merged with it's prototype.
- *
- * @returns {Object} New object with props from both `source` and `changes`.
- */
- export default function protoMerge(source, changes, mergeThreshold = 100) {
- let result;
- const proto = Object.getPrototypeOf(source);
- if (proto === Object.prototype || proto == null) {
- // if source is plain object - inherit result from source
- result = Object.create(source);
- } else {
- const sourceKeys = Object.keys(source);
- const sourceLength = sourceKeys.length;
- if (sourceLength < mergethreshold) {
- result = Object.create(proto);
- // if source size less than threshold - copy source's own props
- for (let i = 0; i < sourceLength; i++) {
- const key = sourceKeys[i]
- result[key] = source[key];
- }
- } else {
- result = {};
- // else - copy all enumerable props from source and it's prototype
- for (const key in source) {
- const value = source[key];
- if (typeof value !== "undefined") {
- result[key] = value;
- }
- }
- }
- }
- // copy all enumerable props from changes object
- for (const key in changes) {
- result[key] = changes[key];
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement