Last active
May 29, 2021 10:41
-
-
Save themgoncalves/5d88dbf146c90850a33ff18a545fb8ea to your computer and use it in GitHub Desktop.
Shallow comparison - validating if two elements are shallow equal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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