Select Git revision

Volker Schukai authored
extend.mjs 1.82 KiB
/**
* Copyright schukai GmbH and contributors 2022. All Rights Reserved.
* Node module: @schukai/monster
* This file is licensed under the AGPLv3 License.
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/
import {isArray, isObject} from "../types/is.mjs";
import {typeOf} from "../types/typeof.mjs";
export {extend}
/**
* Extend copies all enumerable own properties from one or
* more source objects to a target object. It returns the modified target object.
*
* @param {object} target
* @param {object}
* @return {object}
* @license AGPLv3
* @since 1.10.0
* @copyright schukai GmbH
* @memberOf Monster.Data
* @throws {Error} unsupported argument
* @throws {Error} type mismatch
*/
function extend() {
let o, i;
for (i = 0; i < arguments.length; i++) {
let a = arguments[i];
if (!(isObject(a) || isArray(a))) {
throw new Error('unsupported argument ' + JSON.stringify(a));
}
if (o === undefined) {
o = a;
continue;
}
for (let k in a) {
let v = a?.[k];
if (v === o?.[k]) {
continue;
}
if ((isObject(v)&&typeOf(v)==='object') || isArray(v)) {
if (o[k] === undefined) {
if (isArray(v)) {
o[k] = [];
} else {
o[k] = {};
}
} else {
if (typeOf(o[k]) !== typeOf(v)) {
throw new Error("type mismatch: " + JSON.stringify(o[k]) + "(" + typeOf(o[k]) + ") != " + JSON.stringify(v) + "(" + typeOf(v) + ")");
}
}
o[k] = extend(o[k], v);
} else {
o[k] = v;
}
}
}
return o;
}