Last active
October 7, 2024 18:47
-
-
Save rossrobino/2ac79c99d79bc6f3798d4bfba0173a25 to your computer and use it in GitHub Desktop.
DJB2 Hash
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
/** | |
* Fast hashing algorithm for generating etags | |
* http://www.cse.yorku.ca/~oz/hash.html | |
* | |
* taken from sveltekit | |
* https://github.com/sveltejs/kit/blob/25d459104814b0c2dc6b4cf73b680378a29d8200/packages/kit/src/runtime/hash.js | |
*/ | |
const djb2 = (...values: (string | ArrayBufferView)[]) => { | |
let hash = 5381; | |
for (const value of values) { | |
if (typeof value === "string") { | |
let i = value.length; | |
while (i) hash = (hash * 33) ^ value.charCodeAt(--i); | |
} else if (ArrayBuffer.isView(value)) { | |
const buffer = new Uint8Array( | |
value.buffer, | |
value.byteOffset, | |
value.byteLength, | |
); | |
let i = buffer.length; | |
while (i) hash = (hash * 33) ^ buffer[--i]!; | |
} else { | |
throw new TypeError("value must be a string or an ArrayBuffer view"); | |
} | |
} | |
return (hash >>> 0).toString(36); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment