How to get hash value of an object in typescript.
For example :
let user:any = {name:'tempuser', age:'29'};
let anotheruser:any = {name:'iam', age:'29'};
if( Object.GetHashCode(user) === Object.GetHashCode(anotheruser)){
alert('equal');
}
also we can identify the object whether it is modified or not.
AFAIK, neither JavaScript nor TypeScript provide a generic hashing function.
You have to import a third-party lib, like ts-md5 for instance, and give it a string representation of your object: Md5.hashStr(JSON.stringify(yourObject))
.
Obviously, depending on your precise use case, this could be perfect, or way too slow, or generate too many conflicts...
If you want to compare the objects and not the data, then the @Valery solution is not for you, as it will compare the data and not the two objects. If you want to compare the data and not the objects, then JSON.stringify(obj1) === JSON.stringify(obj2) is enough, which is simple string comparison.
For non-crypto uses, like implementing a hash table, here is is the typescript of the venerable java hashCode of a string:
export function hashCode(str: string): number {
var h: number = 0;
for (var i = 0; i < str.length; i++) {
h = 31 * h + str.charCodeAt(i);
}
return h & 0xFFFFFFFF
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With