Last active
February 6, 2018 18:37
-
-
Save davidrapin/cf9fe4dd12a51298b9ae791e10af1bc1 to your computer and use it in GitHub Desktop.
Hash modulo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://www.npmjs.com/package/sha1 | |
var sha1 = require("sha1") | |
// compute (sha1) hash modulo | |
function hash_modulo(str, modulo) { | |
// ignore case of input | |
str = str.toUpperCase(); | |
// compute sha1 of input | |
let h = sha1(str); | |
// use only the 8 last bytes (4 last hex chars) of the sha1 | |
h = h.substr(-4); | |
// append '0x', parse as int, and compute modulo | |
return (+('0x'+h)) % modulo; | |
} | |
// detect collisions | |
const all = new Set(); | |
let col = 0; | |
// print test | |
function t(s) { | |
var h = hash_modulo(s, 40); | |
if (all.has(h)) { col++; } | |
all.add(h); | |
console.log(s + ' ' + h); | |
} | |
// test for various input | |
t('company'); | |
t('market'); | |
t('Investor'); | |
for (let i='a'.charCodeAt(0); i <= 'z'.charCodeAt(0); ++i) { | |
t(String.fromCharCode(i)); | |
} | |
console.log('collisions: ' + col); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment