1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | module.exports = class AssignHelper {
|
7 |
|
8 | static assignUndefined (target, ...sources) {
|
9 | for (const source of sources) {
|
10 | if (source && typeof source === 'object') {
|
11 | for (const key of Object.keys(source)) {
|
12 | if (!Object.prototype.hasOwnProperty.call(target, key)) {
|
13 | target[key] = source[key];
|
14 | }
|
15 | }
|
16 | }
|
17 | }
|
18 | return target;
|
19 | }
|
20 |
|
21 | static deepAssign (target, ...sources) {
|
22 | for (const source of sources) {
|
23 | this._assign(target, source);
|
24 | }
|
25 | return target;
|
26 | }
|
27 |
|
28 | static deepAssignUndefined (target, ...sources) {
|
29 | for (const source of sources) {
|
30 | this._assignUndefined(target, source);
|
31 | }
|
32 | return target;
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 | static _assign (to, from) {
|
38 | if (from && typeof from === 'object') {
|
39 | for (const key of Object.keys(from)) {
|
40 | this._assignProperty(to, from, key);
|
41 | }
|
42 | }
|
43 | return to;
|
44 | }
|
45 |
|
46 | static _assignProperty (to, from, key) {
|
47 | if (!Object.prototype.hasOwnProperty.call(from, key)) {
|
48 | return;
|
49 | }
|
50 | from = from[key];
|
51 | if (from && typeof from === 'object' && !Array.isArray(from)) {
|
52 | if (Object.prototype.hasOwnProperty.call(to, key) && to[key] && typeof to[key] === 'object') {
|
53 | to[key] = this._assign(to[key], from);
|
54 | } else {
|
55 | to[key] = this._assign({}, from);
|
56 | }
|
57 | } else {
|
58 | to[key] = from;
|
59 | }
|
60 | }
|
61 |
|
62 | static _assignUndefined (to, from) {
|
63 | if (from && typeof from === 'object') {
|
64 | for (const key of Object.keys(from)) {
|
65 | this._assignUndefinedProperty(to, from, key);
|
66 | }
|
67 | }
|
68 | return to;
|
69 | }
|
70 |
|
71 | static _assignUndefinedProperty (to, from, key) {
|
72 | if (!Object.prototype.hasOwnProperty.call(from, key)) {
|
73 | return;
|
74 | }
|
75 | from = from[key];
|
76 | if (!Object.prototype.hasOwnProperty.call(to, key)) {
|
77 | return to[key] = from;
|
78 | }
|
79 | to = to[key];
|
80 | if (from && typeof from === 'object' && to && typeof to === 'object') {
|
81 | this._assignUndefined(to, from);
|
82 | }
|
83 | }
|
84 | }; |
\ | No newline at end of file |