Last change
on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1023 bytes
|
Rev | Line | |
---|
[6a3a178] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | /**
|
---|
| 4 | * Module dependenices
|
---|
| 5 | */
|
---|
| 6 |
|
---|
| 7 | const clone = require('shallow-clone');
|
---|
| 8 | const typeOf = require('kind-of');
|
---|
| 9 | const isPlainObject = require('is-plain-object');
|
---|
| 10 |
|
---|
| 11 | function cloneDeep(val, instanceClone) {
|
---|
| 12 | switch (typeOf(val)) {
|
---|
| 13 | case 'object':
|
---|
| 14 | return cloneObjectDeep(val, instanceClone);
|
---|
| 15 | case 'array':
|
---|
| 16 | return cloneArrayDeep(val, instanceClone);
|
---|
| 17 | default: {
|
---|
| 18 | return clone(val);
|
---|
| 19 | }
|
---|
| 20 | }
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | function cloneObjectDeep(val, instanceClone) {
|
---|
| 24 | if (typeof instanceClone === 'function') {
|
---|
| 25 | return instanceClone(val);
|
---|
| 26 | }
|
---|
| 27 | if (instanceClone || isPlainObject(val)) {
|
---|
| 28 | const res = new val.constructor();
|
---|
| 29 | for (let key in val) {
|
---|
| 30 | res[key] = cloneDeep(val[key], instanceClone);
|
---|
| 31 | }
|
---|
| 32 | return res;
|
---|
| 33 | }
|
---|
| 34 | return val;
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 | function cloneArrayDeep(val, instanceClone) {
|
---|
| 38 | const res = new val.constructor(val.length);
|
---|
| 39 | for (let i = 0; i < val.length; i++) {
|
---|
| 40 | res[i] = cloneDeep(val[i], instanceClone);
|
---|
| 41 | }
|
---|
| 42 | return res;
|
---|
| 43 | }
|
---|
| 44 |
|
---|
| 45 | /**
|
---|
| 46 | * Expose `cloneDeep`
|
---|
| 47 | */
|
---|
| 48 |
|
---|
| 49 | module.exports = cloneDeep;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.