From ef1611c44e7382f5a58fbc154de513c15f1a1e59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E4=BD=95=E5=90=8C=E5=AD=A6?= Date: Mon, 11 Mar 2024 16:30:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9Eclone=E3=80=81equal?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/nutui/components/_utils/common.ts | 79 +++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/packages/nutui/components/_utils/common.ts b/packages/nutui/components/_utils/common.ts index 0840cb18..7ae5a7c1 100644 --- a/packages/nutui/components/_utils/common.ts +++ b/packages/nutui/components/_utils/common.ts @@ -1,4 +1,4 @@ -import { isDef, isObject } from './is' +import { isArray, isDef, isObject } from './is' // 变量类型判断 export function TypeOfFun(value: any) { @@ -197,3 +197,80 @@ export function noop() { } export function getRandomId() { return Math.random().toString(36).slice(-8) } + +export function isLooseEqual(a: any, b: any): boolean { + if (a === b) + return true + + const isObjectA = isObject(a) + const isObjectB = isObject(b) + + if (isObjectA && isObjectB) + return JSON.stringify(a) === JSON.stringify(b) + else if (!isObjectA && !isObjectB) + return String(a) === String(b) + else + return false +} + +export function isEqualArray(a: any, b: any): boolean { + if (a === b) + return true + + if (!isArray(a) || !isArray(b)) + return false + + if (a.length !== b.length) + return false + + for (let i = 0; i < a.length; i++) { + if (!isLooseEqual(a[i], b[i])) + return false + } + + return true +} + +export function isEqualValue(a: any, b: any): boolean { + if (a === b) + return true + + if (isArray(a) && isArray(b)) + return isEqualArray(a, b) + + return isLooseEqual(a, b) +} + +export function cloneDeep(obj: T, cache = new WeakMap()): T { + if (obj === null || typeof obj !== 'object') + return obj + if (cache.has(obj)) + return cache.get(obj) + let clone + if (obj instanceof Date) { + clone = new Date(obj.getTime()) + } + else if (obj instanceof RegExp) { + clone = new RegExp(obj) + } + else if (obj instanceof Map) { + clone = new Map(Array.from(obj, ([key, value]) => [key, cloneDeep(value, cache)])) + } + else if (obj instanceof Set) { + clone = new Set(Array.from(obj, value => cloneDeep(value, cache))) + } + else if (Array.isArray(obj)) { + clone = obj.map(value => cloneDeep(value, cache)) + } + else if (Object.prototype.toString.call(obj) === '[object Object]') { + clone = Object.create(Object.getPrototypeOf(obj)) + cache.set(obj, clone) + for (const [key, value] of Object.entries(obj)) + clone[key] = cloneDeep(value, cache) + } + else { + clone = Object.assign({}, obj) + } + cache.set(obj, clone) + return clone +}