Skip to content

Commit

Permalink
feat(utils): 新增 cloneDeepFast 深克隆
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Dec 18, 2020
1 parent 1855780 commit 704704b
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/utils/cloneDeepFast.test.ts
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)
})
})
51 changes: 51 additions & 0 deletions src/utils/cloneDeepFast.ts
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
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from 'lodash-uni'
export * from './base64'
export * from './bindEvent'
export * from './chooseFile'
export * from './cloneDeepFast'
export * from './constantCase'
export * from './copyTextToClipboard'
export * from './createSubmit'
Expand Down

0 comments on commit 704704b

Please sign in to comment.