numberHash.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const SAFE_LIMIT = 0x80000000;
  7. const SAFE_PART = SAFE_LIMIT - 1;
  8. const COUNT = 4;
  9. const arr = [0, 0, 0, 0, 0];
  10. const primes = [3, 7, 17, 19];
  11. module.exports = (str, range) => {
  12. arr.fill(0);
  13. for (let i = 0; i < str.length; i++) {
  14. const c = str.charCodeAt(i);
  15. for (let j = 0; j < COUNT; j++) {
  16. const p = (j + COUNT - 1) % COUNT;
  17. arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART;
  18. }
  19. for (let j = 0; j < COUNT; j++) {
  20. const q = arr[j] % COUNT;
  21. arr[j] = arr[j] ^ (arr[q] >> 1);
  22. }
  23. }
  24. if (range <= SAFE_PART) {
  25. let sum = 0;
  26. for (let j = 0; j < COUNT; j++) {
  27. sum = (sum + arr[j]) % range;
  28. }
  29. return sum;
  30. } else {
  31. let sum1 = 0;
  32. let sum2 = 0;
  33. const rangeExt = Math.floor(range / SAFE_LIMIT);
  34. for (let j = 0; j < COUNT; j += 2) {
  35. sum1 = (sum1 + arr[j]) & SAFE_PART;
  36. }
  37. for (let j = 1; j < COUNT; j += 2) {
  38. sum2 = (sum2 + arr[j]) % rangeExt;
  39. }
  40. return (sum2 * SAFE_LIMIT + sum1) % range;
  41. }
  42. };