Skip to content

Instantly share code, notes, and snippets.

@hrc7505
Last active December 27, 2019 11:53
Show Gist options
  • Save hrc7505/d4eb86ca337ab5c0d7234a5fd4cec631 to your computer and use it in GitHub Desktop.
Save hrc7505/d4eb86ca337ab5c0d7234a5fd4cec631 to your computer and use it in GitHub Desktop.
/**
* A utility to make developer life easy.
*/
class JavascriptUtility{
/**
* Returns `true` if both arguments passed are exactly same by
* type and value; Else returns false.
*/
private static isEqual(value: unknown, other: unknown): boolean{
// Get the value type
const type = Object.prototype.toString.call(value);
// If the two objects are not the same type, return false
if (type !== Object.prototype.toString.call(other)) {
return false;
}
// If items are not an object or array, return false
if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
return false;
}
// Compare the length of the length of the two items
const valueLen = type === '[object Array]'
? (value as unknown[]).length
: Object.keys(value as object).length;
const otherLen = type === '[object Array]'
? (other as unknown[]).length
: Object.keys(other as object).length;
if (valueLen !== otherLen) {
return false;
}
const valueAsArray = value as unknown[];
const otherAsArray = other as unknown[];
// Compare properties
if (type === '[object Array]') {
for (let i = 0; i < valueLen; i++) {
if (JavascriptUtility.compare(valueAsArray[i], otherAsArray[i]) === false) {
return false;
}
}
} else {
for (const key in valueAsArray) {
if (valueAsArray.hasOwnProperty(key)) {
if (JavascriptUtility.compare(valueAsArray[key], otherAsArray[key]) === false) {
return false;
}
}
}
}
// If nothing failed, return true
return true;
};
/**
* Compares two items and returns `true` if match; Else returns `false`.
*/
private static compare(item1: unknown, item2: unknown):boolean{
// Get the object type
const itemType = Object.prototype.toString.call(item1);
// If an object or array, compare recursively
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
if (!JavascriptUtility.isEqual(item1, item2)) {
return false;
}
}
// Otherwise, do a simple comparison
else {
// If the two items are not the same type, return false
if (itemType !== Object.prototype.toString.call(item2)) {
return false;
}
// Else if it's a function, convert to a string and compare
// Otherwise, just compare
if (itemType === '[object Function]') {
if ((item1 as () => void).toString() !== (item2 as () => void).toString()) {
return false;
}
} else {
if (item1 !== item2) {
return false;
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment