hash-functions.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * Copyright (c) 2017 molio contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. // from http://burtleburtle.net/bob/hash/integer.html
  7. export function hash1(i: number) {
  8. let a = i ^ (i >> 4);
  9. a = (a ^ 0xdeadbeef) + (a << 5);
  10. a = a ^ (a >> 11);
  11. return a;
  12. }
  13. export function hash2(i: number, j: number) {
  14. let a = 23;
  15. a = (31 * a + i) | 0;
  16. a = (31 * a + j) | 0;
  17. a = a ^ (a >> 4)
  18. a = (a ^ 0xdeadbeef) + (a << 5);
  19. a = a ^ (a >> 11);
  20. return a;
  21. }
  22. export function hash3(i: number, j: number, k: number) {
  23. let a = 23;
  24. a = (31 * a + i) | 0;
  25. a = (31 * a + j) | 0;
  26. a = (31 * a + k) | 0;
  27. a = a ^ (a >> 4)
  28. a = (a ^ 0xdeadbeef) + (a << 5);
  29. a = a ^ (a >> 11);
  30. return a;
  31. }
  32. export function hash4(i: number, j: number, k: number, l: number) {
  33. let a = 23;
  34. a = (31 * a + i) | 0;
  35. a = (31 * a + j) | 0;
  36. a = (31 * a + k) | 0;
  37. a = (31 * a + l) | 0;
  38. a = a ^ (a >> 4)
  39. a = (a ^ 0xdeadbeef) + (a << 5);
  40. a = a ^ (a >> 11);
  41. return a;
  42. }
  43. /**
  44. * A unique number for each pair of integers
  45. * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
  46. */
  47. export function cantorPairing(a: number, b: number) {
  48. return (a + b) * (a + b + 1) / 2 + b;
  49. }