Skip to content
Snippets Groups Projects
Select Git revision
  • daf062b2d5e5f6abff2c38a4d993eaaca94020e7
  • master default protected
  • 1.31
  • 4.38.3
  • 4.38.2
  • 4.38.1
  • 4.38.0
  • 4.37.2
  • 4.37.1
  • 4.37.0
  • 4.36.0
  • 4.35.0
  • 4.34.1
  • 4.34.0
  • 4.33.1
  • 4.33.0
  • 4.32.2
  • 4.32.1
  • 4.32.0
  • 4.31.0
  • 4.30.1
  • 4.30.0
  • 4.29.1
23 results

extend.mjs

Blame
  • Volker Schukai's avatar
    daf062b2
    History
    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;
    }