Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Hash value of an object in Typescript?

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.

like image 479
Natarajan Ganapathi Avatar asked Apr 23 '16 13:04

Natarajan Ganapathi


3 Answers

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...

like image 74
Valéry Avatar answered Sep 28 '22 06:09

Valéry


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.

like image 33
Muhammad Ishtiaq Hussain Avatar answered Sep 28 '22 07:09

Muhammad Ishtiaq Hussain


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
}
like image 40
Alan Wootton Avatar answered Sep 28 '22 06:09

Alan Wootton