diff --git a/source/data/extend.mjs b/source/data/extend.mjs index b97dddf92bc20f3661f93b63684e81f035406dd9..f2febdc19c13705e19870b00deae1bd8b83aa60b 100644 --- a/source/data/extend.mjs +++ b/source/data/extend.mjs @@ -5,17 +5,15 @@ * 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"; +import {isArray, isObject} from "../types/is.mjs"; +import {typeOf} from "../types/typeof.mjs"; -export { extend }; +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 @@ -24,57 +22,68 @@ export { extend }; * @throws {Error} unsupported argument * @throws {Error} type mismatch * @throws {Error} unsupported argument + * @param args */ function extend(...args) { - let o; - let i; + let o; + let i; - if (typeof args !== "object" || args[0] === null) { - throw new Error(`unsupported argument ${JSON.stringify(args[0])}`); - } + if (typeof args !== "object" || args[0] === null) { + throw new Error(`unsupported argument ${JSON.stringify(args[0])}`); + } - for (i = 0; i < args.length; i++) { - const a = args[i]; + for (i = 0; i < args.length; i++) { + const a = args[i]; - if (!(isObject(a) || isArray(a))) { - throw new Error(`unsupported argument ${JSON.stringify(a)}`); - } + if (!(isObject(a) || isArray(a))) { + throw new Error(`unsupported argument ${JSON.stringify(a)}`); + } - if (o === undefined) { - o = a; - continue; - } + if (o === undefined) { + o = a; + continue; + } - for (const k in a) { - const v = a?.[k]; + for (const k in a) { + const v = a?.[k]; - if (v === o?.[k]) { - continue; - } + 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)})`, - ); - } - } + 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)})`, + ); + } + } + + if (isArray(o[k])) { + o[k] = []; + o[k].push(...v); + continue; + } - o[k] = extend(o[k], v); - } else { - o[k] = v; - } - } - } + o[k] = extend(o[k], v); + } else { + if (isArray(o)) { + o.push(v); + continue; + } + o[k] = v; + } + } + } - return o; + return o; }