/**
* Hashes API endpoint values for development purposes with limited memory.
*
* @param {string} endpoint The API endpoint to hash.
* @param {string} value The value associated with the endpoint.
* @param {number} salt (optional) A salt to add for extra security. Defaults to a random value.
* @returns {string} A hashed representation of the endpoint and value.
*/
function hashApiEndpoint(endpoint, value, salt = Math.random().toString(36).substring(2, 15)) {
// Combine endpoint and value for hashing.
const data = `${endpoint}-${value}`;
// Create a simple hash using a seeded algorithm. Avoids large tables.
let hash = 0;
for (let i = 0; i < data.length; i++) {
hash = (hash * 31 + data.charCodeAt(i)) % 2**32; // Simple polynomial hash
}
// Combine salt for more variation.
hash = (hash ^ salt);
// Convert to a hex string for easy storage and comparison.
return hash.toString(16).padStart(8, '0'); // 8-character hex string
}
// Example Usage:
// const endpoint = "/api/users";
// const userId = 123;
// const hashedValue = hashApiEndpoint(endpoint, userId);
// console.log(hashedValue);
// You can also use it with a specific salt:
// const hashedValueWithSalt = hashApiEndpoint(endpoint, userId, "mySecretSalt");
// console.log(hashedValueWithSalt);
/**
* Helper function to generate a random salt.
* @returns {string} A random salt.
*/
function generateSalt() {
return Math.random().toString(36).substring(2, 15);
}
Add your comment