Skip to content

Instantly share code, notes, and snippets.

@kmsheng
Last active April 8, 2019 07:49
Show Gist options
  • Save kmsheng/c77eead1306ad811e93278fcaccd0f4e to your computer and use it in GitHub Desktop.
Save kmsheng/c77eead1306ad811e93278fcaccd0f4e to your computer and use it in GitHub Desktop.
redux-react-hook / src / shallowEqual.ts
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
// From https://github.com/reduxjs/react-redux/blob/3e53ff96ed10f71c21346f08823e503df724db35/src/utils/shallowEqual.js
const hasOwn = Object.prototype.hasOwnProperty;
// 這個是 Object.is 的 polyfill 版本,應該是給 IE 看的...
function is(x: any, y: any) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y; // 這裡使 +0 與 -0 比對會是 false
} else {
return x !== x && y !== y; // NaN 與 NaN 比對會是 true
}
}
export default function shallowEqual(objA: any, objB: any) {
if (is(objA, objB)) {
return true;
}
// 擋掉不是 object 的情況
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false;
}
// 底下只處理 object
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
// object keys length 不一樣就 return false
if (keysA.length !== keysB.length) {
return false;
}
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < keysA.length; i++) {
// 檢查:
// 1. 每一個 objB 是不是有 keysA[i] 屬性 ?
// 2. objA 與 objB 的值是不是都一樣 ?
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment