Generate a Hash from String in JavaScript

Generate a Hash from string in Javascript

String.prototype.hashCode = function() {
var hash = 0,
i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}

const str = 'revenue'
console.log(str, str.hashCode())

Simple (non-secure) hash function for JavaScript?

I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.

With this prototype you can simply call .hashCode() on any string, e.g. "some string".hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function() {
var hash = 0;
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}

2022 EDIT:

It has been long accepted that modifying built-in prototypes is bad practice, so instead you should use a plain function:

/**
* Returns a hash code from a string
* @param {String} str The string to hash.
* @return {Number} A 32bit integer
* @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
function hashCode(str) {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}

Generate a hash string of an object's reference

It is not possible to get an object's reference in JavaScript in order to calculate a hash of it. The reference is an internal value for the engine that is not normally exposed.

However, if you want to index some data against an object, you can use a Map, since the keys can be any arbitrary JavaScript value, thus allowing objects. Since objects are unique during comparison, that means that the same object returns the value:

class A {
constructor() {
this.a = '1';
}
}

const foo = new A();
const bar = new A();

const map = new Map()
.set(foo, "hello")
.set(bar, "world");

console.log(map.get(foo), map.get(bar));

String to Unique hash in Javascript / Jquery

Here, you can use this simple hashing function:

function hashCode (str){
var hash = 0;
if (str.length == 0) return hash;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}

See the DEMO here

How can I get hash from string and then string from hash back in javascript

You can't. A hash is a one-way function. 560,000 bits cannot be converted into 32 bits and back again.

Make short hash from long string

The shorter the hash, the higher the chances of collision.

However, in the Java world, there is a string hashCode helper that returns a "not so unique" integer out of a string, and it's the smallest way to map a string as ID, but it doesn't guarantee uniqueness and it suffers collisions.

Accordingly, I strongly discourage you to use this in the wild, but for answer sake, here how you can play around with such hash:

function hashCode(s) {
for (var h = 0, i = 0; i < s.length; h &= h)
h = 31 * h + s.charCodeAt(i++);
return h;
}

On the other hand, sha256 is a one way hashing that "doesn't suffer collisions" (it does, but much less than MD5, SHA1, or the hashCode up there), so while the result is a longer unique id, it's kinda granted to always work as expected, and it's explained in MDN.

P.S. NodeJS 15+ has a crypto.webcrypto namespace that is identical to the Web one, so you can use the same code in browsers and server.

Generate random string/characters in JavaScript

I think this will work for you:

function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}

console.log(makeid(5));

Generate deterministic hash number between 0 and 1 from string

You could built an own by using a value for each chatacter with a factor and sum this value. At the end take only fractional part.

This approach may produce collisions.

const decimalHash = string => {

let sum = 0;

for (let i = 0; i < string.length; i++)

sum += (i + 1) * string.codePointAt(i) / (1 << 8)

return sum % 1;

}

console.log(decimalHash('a'));

console.log(decimalHash('aa'));

console.log(decimalHash('hallo world'));

console.log(decimalHash('how are you?'));

console.log(decimalHash('fine, thanks!'));

node.js hash string?

Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
md5sum.update(d);
});

s.on('end', function() {
var d = md5sum.digest('hex');
console.log(d + ' ' + filename);
});


Related Topics



Leave a reply



Submit