1. /**
  2. * Hashes API endpoint values for development purposes with limited memory.
  3. *
  4. * @param {string} endpoint The API endpoint to hash.
  5. * @param {string} value The value associated with the endpoint.
  6. * @param {number} salt (optional) A salt to add for extra security. Defaults to a random value.
  7. * @returns {string} A hashed representation of the endpoint and value.
  8. */
  9. function hashApiEndpoint(endpoint, value, salt = Math.random().toString(36).substring(2, 15)) {
  10. // Combine endpoint and value for hashing.
  11. const data = `${endpoint}-${value}`;
  12. // Create a simple hash using a seeded algorithm. Avoids large tables.
  13. let hash = 0;
  14. for (let i = 0; i < data.length; i++) {
  15. hash = (hash * 31 + data.charCodeAt(i)) % 2**32; // Simple polynomial hash
  16. }
  17. // Combine salt for more variation.
  18. hash = (hash ^ salt);
  19. // Convert to a hex string for easy storage and comparison.
  20. return hash.toString(16).padStart(8, '0'); // 8-character hex string
  21. }
  22. // Example Usage:
  23. // const endpoint = "/api/users";
  24. // const userId = 123;
  25. // const hashedValue = hashApiEndpoint(endpoint, userId);
  26. // console.log(hashedValue);
  27. // You can also use it with a specific salt:
  28. // const hashedValueWithSalt = hashApiEndpoint(endpoint, userId, "mySecretSalt");
  29. // console.log(hashedValueWithSalt);
  30. /**
  31. * Helper function to generate a random salt.
  32. * @returns {string} A random salt.
  33. */
  34. function generateSalt() {
  35. return Math.random().toString(36).substring(2, 15);
  36. }

Add your comment