@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
90 lines (74 loc) • 2.31 kB
text/typescript
/* eslint no-console: off */
import { equals } from "ramda";
const alwaysTrue = () => true;
export const isParentFocusEqual = (
prevParentFocus: ParentFocus,
nextParentFocus: ParentFocus
): boolean => {
return (
prevParentFocus.nextFocusUp === nextParentFocus.nextFocusUp &&
prevParentFocus.nextFocusDown === nextParentFocus.nextFocusDown &&
prevParentFocus.nextFocusRight === nextParentFocus.nextFocusRight &&
prevParentFocus.nextFocusLeft === nextParentFocus.nextFocusLeft
);
};
export const isEqual =
({
byValue = [],
byReference = [],
byComparator = { comparator: alwaysTrue, keys: [] },
debug = false,
compareRemainingKeysBySameValue = false,
}: {
byValue?: string[];
byReference?: string[];
byComparator?: { comparator: (a: any, b: any) => boolean; keys: string[] };
debug?: boolean;
compareRemainingKeysBySameValue?: boolean;
}) =>
(prev, next) => {
for (const key of byReference) {
if (prev[key] !== next[key]) {
if (debug) console.log({ isEqualByReference: false });
return false;
}
}
for (const key of byValue) {
if (!equals(prev[key], next[key])) {
if (debug) console.log({ isEqualByValue: false });
return false;
}
}
for (const key of byComparator.keys) {
if (!byComparator.comparator(prev[key], next[key])) {
if (debug) console.log({ isEqualByComparator: false });
return false;
}
}
if (compareRemainingKeysBySameValue) {
const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
const declaredKeys = new Set([
...byValue,
...byReference,
...byComparator.keys,
]);
for (const key of Array.from(allKeys)) {
if (!declaredKeys.has(key) && !Object.is(prev[key], next[key])) {
if (debug) console.log({ isRestKeysEqualAllBySameValue: false });
return false;
}
}
}
// if we made it here, everything matched
if (debug) {
console.log({
isEqualByValue: true,
isEqualByReference: true,
isEqualByComparator: true,
isRestKeysEqualAllBySameValue: compareRemainingKeysBySameValue
? true
: undefined,
});
}
return true;
};