Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Last active May 29, 2021 10:41
Show Gist options
  • Save themgoncalves/5d88dbf146c90850a33ff18a545fb8ea to your computer and use it in GitHub Desktop.
Save themgoncalves/5d88dbf146c90850a33ff18a545fb8ea to your computer and use it in GitHub Desktop.
Shallow comparison - validating if two elements are shallow equal
import typeOf from './type-of';
const shallowCompare = (source: unknown | unknown[], target: unknown | unknown[]): boolean => {
if (typeOf(source) !== typeOf(target)) {
return false;
}
if (typeOf(source) === 'array') {
return (source as unknown[]).length === (target as unknown[]).length;
} else if (typeOf(source) === 'object') {
return Object.keys(source).every((key) => (source as Record<string, unknown>)[key] === (target as Record<string, unknown>)[key]);
} else if (typeOf(source) === 'date') {
return (source as Date).getTime() === (target as Date).getTime();
}
return source === target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment