Created
July 24, 2018 16:42
-
-
Save JoeKarlsson/b96d86a5d75e0996771847b30ff02aa5 to your computer and use it in GitHub Desktop.
JS Hashing function
This file contains 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
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; |
This file contains 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
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