use-query-params
Version:
React Hook for managing state in URL query parameters with easy serialization.
75 lines (64 loc) • 1.82 kB
text/typescript
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license at
* https://github.com/facebook/fbjs/blob/master/LICENSE
*/
/*eslint-disable no-self-compare */
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x: any, y: any): boolean {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
* @pbeshai modification of shallowEqual to take into consideration a map providing
* equals functions
*/
export default function shallowEqual(
objA: any,
objB: any,
equalMap?: any
): boolean {
if (is(objA, objB)) {
return true;
}
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (let i = 0; i < keysA.length; i++) {
const isEqual = equalMap?.[keysA[i]]?.equals ?? is;
if (
!hasOwnProperty.call(objB, keysA[i]) ||
!isEqual(objA[keysA[i]], objB[keysA[i]])
) {
return false;
}
}
return true;
}