Skip to content

Commit

Permalink
[docs] 完善 deepClone 工具方法文档
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhang-Wei-666 committed Aug 16, 2023
1 parent 8e8787e commit 68641f8
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
60 changes: 60 additions & 0 deletions packages/mixte/src/deepClone/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
outline: [3,4]
---

- 创建传入值的深拷贝
- 只会深拷贝普通对象和数组, 其他类型的值会直接被继承

### 类型

```ts
function deepClone<T>(value: T): T;
```

### 示例

<br>

#### 深拷贝对象

```ts
import { deepClone } from 'mixte';

const obj = {
a: { b: 2 }
};

const cloneObj = deepClone(obj);

console.log(obj === cloneObj); // -> false
console.log(obj.a === cloneObj.a); // -> false
```

#### 深拷贝数组

```ts
import { deepClone } from 'mixte';

const arr = [{ a: 1 }, { b: 2 }];

const cloneArr = deepClone(arr);

console.log(arr === cloneArr); // -> false
console.log(arr[0] === cloneArr[0]); // -> false
console.log(arr[1] === cloneArr[1]); // -> false
```

#### 支持防御循环引用

```js
const obj = {};
obj.obj = obj;

const cloneObj = deepClone(obj);

console.log(obj.obj === obj); // -> true
console.log(cloneObj.obj === cloneObj); // -> true

console.log(obj === cloneObj); // -> false
console.log(obj.obj === cloneObj.obj); // -> false
```
9 changes: 9 additions & 0 deletions packages/mixte/src/deepClone/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ function clone<T>(value: T, cache = new WeakMap<object, object>()) {
/**
* 创建传入值的深拷贝
* - 只会深拷贝普通对象和数组, 其他类型的值会直接被继承
* @example
* const obj = {
* a: { b: 2 }
* };
*
* const cloneObj = deepClone(obj);
*
* console.log(obj === cloneObj); // -> false
* console.log(obj.a === cloneObj.a); // -> false
*/
export function deepClone<T>(value: T): T {
return clone(value);
Expand Down

0 comments on commit 68641f8

Please sign in to comment.