Convert long strings into short, url-safe, hash-like strings. Limited to 32 bits of uniqueness.
npm install hash-code-stringhash-code-string is a small utility package to convert long strings into shorter, hash-like strings. It provides functions to create hashes, encode them in a URL-safe base64 format, and decode them back into bytes, or a 32 bit number if desired. Limited to 32 bits of uniqueness. No dependencies, the hashing code is 5 lines. Assumes environment has Uint8Array, Math.imul, and btoa.
``sh`
npm install hash-code-string
`sh`
pnpm install hash-code-string
`javascript
import { hashString, hashToNum32 } from 'hash-code-string';
// Example usage
const longString = "This is a long string that needs to be hashed";
const hash = hashString(longString);
console.log(Hash: ${hash}); // Hash: g3g2qw
const decodedHash = hashToNum32(hash);
console.log(Decoded Hash: ${decodedHash}); // Decoded Hash: -1422493565`
Parameters:
* str: The input string to hash.
Returns:
A 32-bit integer hash code.
Parameters:
* num: The 32-bit integer to split.
Returns:
A Uint8Array containing 4 bytes.
Parameters:
* bytes: An array of bytes.
Returns:
A string representing the byte values.
Parameters:
* str: The input string to encode.
Returns:
A URL-safe base64 encoded string.
Parameters:
* str: The input string to hash and encode.
Returns:
A URL-safe base64 encoded hash string.
Parameters:
* str: The URL-safe base64 string to decode.
Returns:
The decoded string.
Parameters:
* str: The input string.
Returns:
An array of character codes.
Parameters:
* bytes: An array of bytes.
Returns:
A 32-bit integer.
`javascript
const str = "example";
const hash = hashString(str);
console.log(hash); // Output: URL-safe base64 encoded hash
const decoded = decode64(hash);
console.log(decoded); // Output: decoded hash string
const charCodes = stringToCodes(decoded);
console.log(charCodes); // Output: Array of character codes
const num = bytesToNum32(charCodes);
console.log(num); // Output: 32-bit number
``
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the ISC License. See the LICENSE file for details.