Guest User

Untitled

a guest
Nov 14th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. function getKeys(trie) {
  2. return Object.keys(trie).filter(x => x !== 'hash');
  3. }
  4.  
  5. function keyToTimestamp(key) {
  6. // 16 is the length of the base 3 value of the current time in
  7. // minutes. Ensure it's padded to create the full value
  8. let fullkey = key + '0'.repeat(16 - key.length);
  9.  
  10. // Parse the base 3 representation
  11. return parseInt(fullkey, 3) * 1000 * 60;
  12. }
  13.  
  14. export function insert(trie, timestamp) {
  15. let hash = timestamp.hash();
  16. let key = Number((timestamp.millis() / 1000 / 60) | 0).toString(3);
  17.  
  18. trie = Object.assign({}, trie, { hash: trie.hash ^ hash });
  19. return insertKey(trie, key, hash);
  20. }
  21.  
  22. export function insertKey(trie, key, hash) {
  23. if (key.length === 0) {
  24. return trie;
  25. }
  26. const c = key[0];
  27. const n = trie[c] || {};
  28. return Object.assign({}, trie, {
  29. [c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
  30. hash: n.hash ^ hash
  31. })
  32. });
  33. }
  34.  
  35. export function build(timestamps) {
  36. let trie = {};
  37. for (let timestamp of timestamps) {
  38. insert(trie, timestamp);
  39. }
  40. return trie;
  41. }
  42.  
  43. export function diff(trie1, trie2) {
  44. if (trie1.hash === trie2.hash) {
  45. return null;
  46. }
  47.  
  48. let node1 = trie1;
  49. let node2 = trie2;
  50. let k = '';
  51.  
  52. while (1) {
  53. let keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
  54. let keys = [...keyset.values()];
  55. keys.sort();
  56.  
  57. let diffkey = keys.find(key => {
  58. let next1 = node1[key] || {};
  59. let next2 = node2[key] || {};
  60. return next1.hash !== next2.hash;
  61. });
  62. if (!diffkey) {
  63. return keyToTimestamp(k);
  64. }
  65.  
  66. k += diffkey;
  67. node1 = node1[diffkey] || {};
  68. node2 = node2[diffkey] || {};
  69. }
  70. }
  71.  
  72. export function prune(trie, n = 2) {
  73. let keys = getKeys(trie);
  74. keys.sort();
  75.  
  76. let next = { hash: trie.hash };
  77. keys = keys.slice(-n).map(k => (next[k] = prune(trie[k], n)));
  78.  
  79. return next;
  80. }
  81.  
  82. export function debug(trie, k = '', indent = 0) {
  83. const str =
  84. ' '.repeat(indent) + (k !== '' ? `k: ${k} ` : '') + `hash: ${trie.hash}\n`;
  85. return (
  86. str +
  87. getKeys(trie)
  88. .map(key => {
  89. return debug(trie[key], key, indent + 2);
  90. })
  91. .join('')
  92. );
  93. }
Add Comment
Please, Sign In to add comment