Once, I wrote about hash function that I improved. Though, that was C#. In this post I will show you how to get hash code with Java Script. (previous post)
function getStableHash(input,hashLength) { /* Copyright (C) 2012 Artem Los, * All rights reserved. * * code based on: * http://blog.clizware.net/news/631 * * originaly from: http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp */ var _length = Math.pow(10,hashLength); //result in 10 numbers, if hashLength is 10 var hash = 0; for (var j = 0; j < input.length; j++) { hash += input.charCodeAt(j); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); var result = ((hash % _length) + _length) % _length;//hash.mod(_length) var check = parseInt(_length / result); if (check > 1) { result *= check; } return result; }
In order to calculate a hash value, you need to define two main variables. First of all, the string to calculate hash from (input), and eventually, the length of the result (hashLength). It is recommended that you set the hashLength to 8 or in some cases 10.
Please take a look at this code in work http://editor.clizware.net/?id=9
Leave a Reply