simple string hash generation

by Laurens Maneschijn

HTML

put any string here:<br>
<textarea></textarea><br>

numeric hash appears here:<br>
<input readonly><br>

JavaScript

// https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
// https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript/8831937#8831937
// https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
// NB: this is not a secure hash, but it is quick, and should not have a lot of collissions.
simple_string_hash = function(s) {
	var i, c, hash = 0, strlen = s.length;
	if ( strlen === 0 ) {
		return hash;
	}
	for ( i = 0; i < strlen; i++ ) {
		c = s.charCodeAt( i );
		hash = ((hash << 5) - hash) + c;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
};

// 1 line for copy pasting:
simple_string_hash2 = function(s){for(var h=0,i=0;i<s.length;i++){h=((h<<5)-h)+s.charCodeAt(i);h&=h;}return h};


function update() {
	var s = document.querySelector('textarea').value;
	var s = document.querySelector('input').value = simple_string_hash(s);
}

document.querySelector('textarea').addEventListener('change', update);
document.querySelector('textarea').addEventListener('keyup', update);