hash-functions.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright (c) 2017 mol* 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. export function hashString(s: string) {
  44. let h = 0;
  45. for (let i = 0, l = s.length; i < l; i++) {
  46. h = (h << 5) - h + s.charCodeAt(i++) | 0;
  47. }
  48. return h;
  49. }
  50. /**
  51. * A unique number for each pair of integers
  52. * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
  53. */
  54. export function cantorPairing(a: number, b: number) {
  55. return (a + b) * (a + b + 1) / 2 + b;
  56. }
  57. /**
  58. * A unique number for each sorted pair of integers
  59. * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
  60. */
  61. export function sortedCantorPairing(a: number, b: number) {
  62. return a < b ? cantorPairing(a, b) : cantorPairing(b, a);
  63. }