-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { cloneDeepFast } from './cloneDeepFast' | ||
|
||
describe('cloneDeepFast', () => { | ||
test('表现正常', () => { | ||
const value = { x: [1] } | ||
expect(cloneDeepFast(value)).not.toBe(value) | ||
expect(cloneDeepFast(value).x).not.toBe(value.x) | ||
expect(cloneDeepFast(value)).toEqual(value) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// @ts-nocheck | ||
// Copyright 2019 "David Mark Clements <[email protected]>" | ||
// MIT Licensed | ||
// https://github.com/davidmarkclements/rfdc | ||
// Modified by Jay Fong | ||
/** | ||
* 深克隆快速版。 | ||
* | ||
* @param value 要克隆的值 | ||
* @returns 返回克隆后的值 | ||
* @example | ||
* ```typescript | ||
* cloneDeepFast({ x: [1] }) | ||
* // => { x: [1] } | ||
* ``` | ||
*/ | ||
export function cloneDeepFast<T>(value: T): T { | ||
if (typeof value !== 'object' || value === null) return value | ||
if (value instanceof Date) return new Date(value) | ||
if (Array.isArray(value)) return cloneArray(value) | ||
const o2 = {} | ||
for (const k in value) { | ||
if (Object.hasOwnProperty.call(value, k) === false) continue | ||
const cur = value[k] | ||
if (typeof cur !== 'object' || cur === null) { | ||
o2[k] = cur | ||
} else if (cur instanceof Date) { | ||
o2[k] = new Date(cur) | ||
} else { | ||
o2[k] = cloneDeepFast(cur) | ||
} | ||
} | ||
return o2 | ||
} | ||
|
||
function cloneArray(a) { | ||
const keys = Object.keys(a) | ||
const a2 = new Array(keys.length) | ||
for (let i = 0; i < keys.length; i++) { | ||
const k = keys[i] | ||
const cur = a[k] | ||
if (typeof cur !== 'object' || cur === null) { | ||
a2[k] = cur | ||
} else if (cur instanceof Date) { | ||
a2[k] = new Date(cur) | ||
} else { | ||
a2[k] = cloneDeepFast(cur) | ||
} | ||
} | ||
return a2 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters