hash-functions.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. // from http://burtleburtle.net/bob/hash/integer.html
  8. export function hash1(i: number) {
  9. let a = i ^ (i >> 4);
  10. a = (a ^ 0xdeadbeef) + (a << 5);
  11. a = a ^ (a >> 11);
  12. return a;
  13. }
  14. export function hash2(i: number, j: number) {
  15. let a = 23;
  16. a = (31 * a + i) | 0;
  17. a = (31 * a + j) | 0;
  18. a = a ^ (a >> 4);
  19. a = (a ^ 0xdeadbeef) + (a << 5);
  20. a = a ^ (a >> 11);
  21. return a;
  22. }
  23. export function hash3(i: number, j: number, k: number) {
  24. let a = 23;
  25. a = (31 * a + i) | 0;
  26. a = (31 * a + j) | 0;
  27. a = (31 * a + k) | 0;
  28. a = a ^ (a >> 4);
  29. a = (a ^ 0xdeadbeef) + (a << 5);
  30. a = a ^ (a >> 11);
  31. return a;
  32. }
  33. export function hash4(i: number, j: number, k: number, l: number) {
  34. let a = 23;
  35. a = (31 * a + i) | 0;
  36. a = (31 * a + j) | 0;
  37. a = (31 * a + k) | 0;
  38. a = (31 * a + l) | 0;
  39. a = a ^ (a >> 4);
  40. a = (a ^ 0xdeadbeef) + (a << 5);
  41. a = a ^ (a >> 11);
  42. return a;
  43. }
  44. export function hashString(s: string) {
  45. let h = 0;
  46. for (let i = 0, l = s.length; i < l; i++) {
  47. h = (h << 5) - h + s.charCodeAt(i++) | 0;
  48. }
  49. return h;
  50. }
  51. /**
  52. * A unique number for each pair of integers
  53. * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
  54. */
  55. export function cantorPairing(a: number, b: number) {
  56. return (a + b) * (a + b + 1) / 2 + b;
  57. }
  58. /**
  59. * A unique number for each sorted pair of integers
  60. * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
  61. */
  62. export function sortedCantorPairing(a: number, b: number) {
  63. return a < b ? cantorPairing(a, b) : cantorPairing(b, a);
  64. }
  65. /**
  66. * 32 bit FNV-1a hash, see http://isthe.com/chongo/tech/comp/fnv/
  67. */
  68. export function hashFnv32a(array: ArrayLike<number>) {
  69. let hval = 0x811c9dc5;
  70. for (let i = 0, il = array.length; i < il; ++i) {
  71. hval ^= array[i];
  72. hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
  73. }
  74. return hval >>> 0;
  75. }