finki-main
main
|
Last change
on this file since 62b2964 was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago |
|
Initial commit
|
-
Property mode
set to
100644
|
|
File size:
1.2 KB
|
| Line | |
|---|
| 1 | var clone = require('./clone');
|
|---|
| 2 |
|
|---|
| 3 | module.exports = merge;
|
|---|
| 4 |
|
|---|
| 5 | function typesMatch(a, b) {
|
|---|
| 6 | return (typeof a === typeof b) && (Array.isArray(a) === Array.isArray(b));
|
|---|
| 7 | }
|
|---|
| 8 |
|
|---|
| 9 | /**
|
|---|
| 10 | * A deep merge of the source based on the target.
|
|---|
| 11 | * @param {Object} source [description]
|
|---|
| 12 | * @param {Object} target [description]
|
|---|
| 13 | * @return {Object} [description]
|
|---|
| 14 | */
|
|---|
| 15 | function merge(source, target, result) {
|
|---|
| 16 | if (result === undefined) {
|
|---|
| 17 | result = clone(source);
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | // merge missing values from the target to the source
|
|---|
| 21 | Object.getOwnPropertyNames(target).forEach(function (key) {
|
|---|
| 22 | if (source[key] === undefined) {
|
|---|
| 23 | result[key] = target[key];
|
|---|
| 24 | }
|
|---|
| 25 | });
|
|---|
| 26 |
|
|---|
| 27 | Object.getOwnPropertyNames(source).forEach(function (key) {
|
|---|
| 28 | var value = source[key];
|
|---|
| 29 |
|
|---|
| 30 | if (target[key] && typesMatch(value, target[key])) {
|
|---|
| 31 | // merge empty values
|
|---|
| 32 | if (value === '') {
|
|---|
| 33 | result[key] = target[key];
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | if (Array.isArray(value)) {
|
|---|
| 37 | if (value.length === 0 && target[key].length) {
|
|---|
| 38 | result[key] = target[key].slice(0);
|
|---|
| 39 | }
|
|---|
| 40 | } else if (typeof value === 'object') {
|
|---|
| 41 | result[key] = merge(value, target[key]);
|
|---|
| 42 | }
|
|---|
| 43 | }
|
|---|
| 44 | });
|
|---|
| 45 |
|
|---|
| 46 | return result;
|
|---|
| 47 | } |
|---|
Note:
See
TracBrowser
for help on using the repository browser.