Skip to content

Instantly share code, notes, and snippets.

@paullaffitte
Last active May 16, 2020 17:48
Show Gist options
  • Save paullaffitte/b0f0b43be1f0f6a417463fb5a6d50feb to your computer and use it in GitHub Desktop.
Save paullaffitte/b0f0b43be1f0f6a417463fb5a6d50feb to your computer and use it in GitHub Desktop.
Hash for fun
const inputs = [
'Bonjour monsieur Dupont ! Comment allez-vous ?..',
'Bonjour monsieur Dupont ! Comment allez-vous ?',
'Bonjour monsieur Dupond ! Comment allez-vous ?',
'test',
'testt',
'tests',
'a',
'A',
'B',
'C',
'',
];
const hash = (input) => {
const chars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
const outputSize = 32;
const output = Array.apply(null, { length: outputSize }).map(() => 0);
const inputNumbers = input.split('').map((c, i) => input.charCodeAt(i));
const firstSum = (inputNumbers.reduce((acc, v) => acc + v, 0) + inputNumbers.length) % (outputSize + 1);
while (inputNumbers.length < outputSize) {
const index = inputNumbers[outputSize % inputNumbers.length] % inputNumbers.length;
const newData = inputNumbers[index] || 0;
inputNumbers.push(newData + inputNumbers.length);
}
while (inputNumbers.length) {
for (let i = 0; i < outputSize && inputNumbers.length > 0; i++) {
output[i] += inputNumbers.pop() + firstSum;
}
}
return output.map(c => chars[c % chars.length]).join('');
}
console.log(inputs.map(input => ({ output: hash(input), input })));
const start = Date.now();
const getDelta = () => (Date.now() - start) / 1000;
const hashes = [];
const charMax = Math.pow(2, 16);
for (let i = 0; i < charMax; i++) {
hashes.push(hash(String.fromCharCode(i)));
}
console.log(hashes);
console.log(`Generated in ${getDelta()} seconds`);
const showProgress = i => {
i += 1;
const percent = i / charMax * 100;
console.log(`${i}/${charMax}\t`, Math.round(percent * 100) / 100 + '%\t', getDelta() + 's');
};
for (let i = 0; i < charMax; i++) {
const needle = hashes.pop();
for (let j = 0; j < hashes.length; j++) {
if (hashes[j] == needle) {
console.log('Conflict found', i);
process.exit(1);
}
}
if (i % 1000 == 0) {
showProgress(i);
}
}
showProgress(charMax - 1);
console.log('No conflict found!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment