[js函数] shallowEqual

const isBasicType = (t: any) => {
return t === "number" || t === "string" || t === "boolean" || t === 'undefined';
}


/**
* 数组和对象都能比较
* @param a
* @param b
* @returns {boolean}
*/
function compareByObject(a:any,b:any){
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
return false;
}

const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b);
for (let idx = 0; idx < keysA.length; idx++) {
const key = keysA[idx];
if (!bHasOwnProperty(key) || a[key] !== b[key]) {
return false;
}
}
return true;
}



const shallowEqual = (a:any, b:any) => {

const aType = typeof a;
const bType = typeof b;

if (aType !== bType) {
return false;
}

if (isBasicType(aType) && isBasicType(bType)) {
return a === b;
}


if (typeof a !== "object" || !a || typeof b !== "object" || !b) {
return false;
}

if (a === b) {
return true;
}

return compareByObject(a,b);
};


export {
shallowEqual
}
posted on 2023-02-16 19:23  袜子破了  阅读(65)  评论(0编辑  收藏  举报