2020-07-15 21:37:51 +08:00
|
|
|
import { isArray, isDate, isObject } from './'
|
|
|
|
|
|
|
|
function looseCompareArrays(a: any[], b: any[]) {
|
|
|
|
if (a.length !== b.length) return false
|
|
|
|
let equal = true
|
|
|
|
for (let i = 0; equal && i < a.length; i++) {
|
|
|
|
equal = looseEqual(a[i], b[i])
|
|
|
|
}
|
|
|
|
return equal
|
|
|
|
}
|
2020-02-06 03:23:03 +08:00
|
|
|
|
|
|
|
export function looseEqual(a: any, b: any): boolean {
|
|
|
|
if (a === b) return true
|
2020-07-15 21:37:51 +08:00
|
|
|
let aValidType = isDate(a)
|
|
|
|
let bValidType = isDate(b)
|
|
|
|
if (aValidType || bValidType) {
|
|
|
|
return aValidType && bValidType ? a.getTime() === b.getTime() : false
|
|
|
|
}
|
|
|
|
aValidType = isArray(a)
|
|
|
|
bValidType = isArray(b)
|
|
|
|
if (aValidType || bValidType) {
|
|
|
|
return aValidType && bValidType ? looseCompareArrays(a, b) : false
|
|
|
|
}
|
|
|
|
aValidType = isObject(a)
|
|
|
|
bValidType = isObject(b)
|
|
|
|
if (aValidType || bValidType) {
|
|
|
|
/* istanbul ignore if: this if will probably never be called */
|
|
|
|
if (!aValidType || !bValidType) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
const aKeysCount = Object.keys(a).length
|
|
|
|
const bKeysCount = Object.keys(b).length
|
|
|
|
if (aKeysCount !== bKeysCount) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for (const key in a) {
|
|
|
|
const aHasKey = a.hasOwnProperty(key)
|
|
|
|
const bHasKey = b.hasOwnProperty(key)
|
|
|
|
if (
|
|
|
|
(aHasKey && !bHasKey) ||
|
|
|
|
(!aHasKey && bHasKey) ||
|
|
|
|
!looseEqual(a[key], b[key])
|
|
|
|
) {
|
2020-02-06 03:23:03 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-15 21:37:51 +08:00
|
|
|
return String(a) === String(b)
|
2020-02-06 03:23:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export function looseIndexOf(arr: any[], val: any): number {
|
|
|
|
return arr.findIndex(item => looseEqual(item, val))
|
|
|
|
}
|