Skip to content

Instantly share code, notes, and snippets.

@JoeKarlsson
Created July 24, 2018 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeKarlsson/b96d86a5d75e0996771847b30ff02aa5 to your computer and use it in GitHub Desktop.
Save JoeKarlsson/b96d86a5d75e0996771847b30ff02aa5 to your computer and use it in GitHub Desktop.
JS Hashing function
const hashAlgorithm = (data) => {
const FNV_PRIME_32 = 0x1000193;
const FNV_OFFSET_32 = 0x811C9DC5;
let hash = FNV_OFFSET_32;
const str = JSON.stringify(data);
for (let i = 0; i < str.length; i++) {
hash ^= str.charCodeAt(i);
hash *= FNV_PRIME_32;
}
return hash;
};
export default hashAlgorithm;
import hash from './hash';
describe('#fnv32 Hash Function', () => {
it('should generate a number hash', () => {
const data = JSON.stringify([ { foo: 'bar' }, { baz: 'spaz' } ]);
expect(typeof (hash(data))).toBe('number');
});
it('should generate a 32 signed bit hash', () => {
const data = JSON.stringify([ { foo: 'bar' }, { baz: 'spaz' } ]);
const bitCheck = hash(data) >> 31;
expect(bitCheck).toEqual(0);
});
it('should return the same hash for the same object', () => {
const data = JSON.stringify([ { foo: 'bar' }, { baz: 'spaz' } ]);
const hash1 = hash(data);
const hash2 = hash(data);
expect(hash1).toBe(hash2);
});
it('should return the different hashes for the different objects', () => {
const data1 = JSON.stringify([ { foo: 'bar' }, { baz: 'spaz' } ]);
const data2 = JSON.stringify([ { foo: 'bars' }, { baz: 'spazz' } ]);
const hash1 = hash(data1);
const hash2 = hash(data2);
expect(hash1).not.toBe(hash2);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment