UNPKG

1.95 kBJavaScriptView Raw
1/**
2 * @fileoverview Common utilities.
3 */
4"use strict";
5
6//------------------------------------------------------------------------------
7// Public Interface
8//------------------------------------------------------------------------------
9/**
10 * Merges two objects together and assigns the result to the initial object. Can be used for shallow cloning.
11 * @param {Object} target of the cloning operation
12 * @param {Object} source object
13 * @returns {void}
14 */
15exports.mixin = function(target, source) {
16 Object.keys(source).forEach(function(key) {
17 target[key] = source[key];
18 });
19};
20
21/**
22 * Merges two config objects. This will not only add missing keys, but will also modify values to match.
23 * @param {Object} base config object
24 * @param {Object} custom config object. Overrides in this config object will take priority over base.
25 * @returns {Object} merged config object.
26 */
27exports.mergeConfigs = function mergeConfigs(base, custom) {
28
29 Object.keys(custom).forEach(function (key) {
30 var property = custom[key];
31
32 if (key === "plugins") {
33 if (!base[key]) {
34 base[key] = [];
35 }
36
37 property.forEach(function (plugin) {
38 // skip duplicates
39 if (base[key].indexOf(plugin) === -1) {
40 base[key].push(plugin);
41 }
42 });
43 return;
44 }
45
46 if (Array.isArray(base[key]) && !Array.isArray(property) && typeof property === "number") {
47 //assume that we are just overriding first attribute
48 base[key][0] = custom[key];
49 return;
50 }
51
52 if (typeof property === "object" && !Array.isArray(property)) {
53 // base[key] might not exist, so be careful with recursion here
54 base[key] = mergeConfigs(base[key] || {}, custom[key]);
55 } else {
56 base[key] = custom[key];
57 }
58 });
59
60 return base;
61};