1 | // Copyright 2012 Mark Cavage, Inc. All rights reserved.
|
2 |
|
3 | ;
|
4 |
|
5 | /**
|
6 | * Return a shallow copy of the given object;
|
7 | *
|
8 | * @public
|
9 | * @function shallowCopy
|
10 | * @param {Object} obj - the object to copy
|
11 | * @returns {Object} the new copy of the object
|
12 | */
|
13 | function shallowCopy(obj) {
|
14 | if (!obj) {
|
15 | return obj;
|
16 | }
|
17 | var copy = {};
|
18 | Object.keys(obj).forEach(function forEach(k) {
|
19 | copy[k] = obj[k];
|
20 | });
|
21 | return copy;
|
22 | }
|
23 |
|
24 | /**
|
25 | * Merges two query parameter objects. Merges to array
|
26 | * if the same key is encountered.
|
27 | *
|
28 | * @public
|
29 | * @function mergeQs
|
30 | * @param {Object} obj1 - first qs object
|
31 | * @param {Object} obj2 - second qs object
|
32 | * @returns {Object} the merged object
|
33 | */
|
34 | function mergeQs(obj1, obj2) {
|
35 | var merged = shallowCopy(obj1) || {};
|
36 |
|
37 | // defend against null cause null is an object. yay js.
|
38 | if (obj2 && typeof obj2 === 'object') {
|
39 | Object.keys(obj2).forEach(function forEach(key) {
|
40 | // if we already have this key and it isn't an array,
|
41 | // make it one array of the same element.
|
42 | if (merged.hasOwnProperty(key) && !(merged[key] instanceof Array)) {
|
43 | merged[key] = [merged[key]];
|
44 |
|
45 | // push the new value down
|
46 | merged[key].push(obj2[key]);
|
47 | } else {
|
48 | // otherwise just set it
|
49 | merged[key] = obj2[key];
|
50 | }
|
51 | });
|
52 | }
|
53 |
|
54 | return merged;
|
55 | }
|
56 |
|
57 | ///--- Exports
|
58 |
|
59 | module.exports = {
|
60 | shallowCopy: shallowCopy,
|
61 | mergeQs: mergeQs
|
62 | };
|