-
Notifications
You must be signed in to change notification settings - Fork 16
/
hamt.js
853 lines (715 loc) · 22 KB
/
hamt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/**
@fileOverview Hash Array Mapped Trie.
Code based on: https://github.com/exclipy/pdata
*/
var hamt = {}; // export
/* Configuration
******************************************************************************/
var SIZE = 5;
var BUCKET_SIZE = Math.pow(2, SIZE);
var MASK = BUCKET_SIZE - 1;
var MAX_INDEX_NODE = BUCKET_SIZE / 2;
var MIN_ARRAY_NODE = BUCKET_SIZE / 4;
/*
******************************************************************************/
var defaultValBind = function defaultValBind(f, defaultValue) {
return function (x) {
return f(arguments.length === 0 ? defaultValue : x);
};
};
/**
Get 32 bit hash of string.
Based on:
http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
*/
var hash = hamt.hash = function (str) {
var type = typeof str === 'undefined' ? 'undefined' : _typeof(str);
if (type === 'number') return str;
if (type !== 'string') str += '';
var hash = 0;
for (var i = 0, len = str.length; i < len; ++i) {
var c = str.charCodeAt(i);
hash = (hash << 5) - hash + c | 0;
}
return hash;
};
/* Bit Ops
******************************************************************************/
/**
Hamming weight.
Taken from: http://jsperf.com/hamming-weight
*/
var popcount = function popcount(x) {
x -= x >> 1 & 0x55555555;
x = (x & 0x33333333) + (x >> 2 & 0x33333333);
x = x + (x >> 4) & 0x0f0f0f0f;
x += x >> 8;
x += x >> 16;
return x & 0x7f;
};
var hashFragment = function hashFragment(shift, h) {
return h >>> shift & MASK;
};
var toBitmap = function toBitmap(x) {
return 1 << x;
};
var fromBitmap = function fromBitmap(bitmap, bit) {
return popcount(bitmap & bit - 1);
};
/* Array Ops
******************************************************************************/
/**
Set a value in an array.
@param at Index to change.
@param v New value
@param arr Array.
*/
var arrayUpdate = function arrayUpdate(at, v, arr) {
var len = arr.length;
var out = new Array(len);
for (var i = 0; i < len; ++i) {
out[i] = arr[i];
}out[at] = v;
return out;
};
/**
Remove a value from an array.
@param at Index to remove.
@param arr Array.
*/
var arraySpliceOut = function arraySpliceOut(at, arr) {
var len = arr.length;
var out = new Array(len - 1);
var i = 0,
g = 0;
while (i < at) {
out[g++] = arr[i++];
}++i;
while (i < len) {
out[g++] = arr[i++];
}return out;
};
/**
Insert a value into an array.
@param at Index to insert at.
@param v Value to insert,
@param arr Array.
*/
var arraySpliceIn = function arraySpliceIn(at, v, arr) {
var len = arr.length;
var out = new Array(len + 1);
var i = 0,
g = 0;
while (i < at) {
out[g++] = arr[i++];
}out[g++] = v;
while (i < len) {
out[g++] = arr[i++];
}return out;
};
/* Node Structures
******************************************************************************/
var LEAF = 1;
var COLLISION = 2;
var INDEX = 3;
var ARRAY = 4;
/**
Leaf holding a value.
@member hash Hash of key.
@member key Key.
@member value Value stored.
*/
var Leaf = function Leaf(hash, key, value) {
return {
type: LEAF,
hash: hash,
key: key,
value: value,
_modify: Leaf__modify
};
};
/**
Leaf holding multiple values with the same hash but different keys.
@member hash Hash of key.
@member children Array of collision children node.
*/
var Collision = function Collision(hash, children) {
return {
type: COLLISION,
hash: hash,
children: children,
_modify: Collision__modify
};
};
/**
Internal node with a sparse set of children.
Uses a bitmap and array to pack children.
@member mask Bitmap that encode the positions of children in the array.
@member children Array of child nodes.
*/
var IndexedNode = function IndexedNode(mask, children) {
return {
type: INDEX,
mask: mask,
children: children,
_modify: IndexedNode__modify
};
};
/**
Internal node with many children.
@member size Number of children.
@member children Array of child nodes.
*/
var ArrayNode = function ArrayNode(size, children) {
return {
type: ARRAY,
size: size,
children: children,
_modify: ArrayNode__modify
};
};
/**
Is `node` a leaf node?
*/
var isLeaf = function isLeaf(node) {
return node.type === LEAF || node.type === COLLISION;
};
/* Internal node operations.
******************************************************************************/
/**
Expand an indexed node into an array node.
@param frag Index of added child.
@param child Added child.
@param mask Index node mask before child added.
@param subNodes Index node children before child added.
*/
var expand = function expand(frag, child, bitmap, subNodes) {
var arr = [];
var bit = bitmap;
var count = 0;
for (var i = 0; bit; ++i) {
if (bit & 1) arr[i] = subNodes[count++];
bit >>>= 1;
}
arr[frag] = child;
return ArrayNode(count + 1, arr);
};
/**
Collapse an array node into a indexed node.
@param count Number of elements in new array.
@param removed Index of removed element.
@param elements Array node children before remove.
*/
var pack = function pack(count, removed, elements) {
var children = new Array(count - 1);
var g = 0;
var bitmap = 0;
for (var i = 0, len = elements.length; i < len; ++i) {
if (i !== removed) {
var elem = elements[i];
if (elem) {
children[g++] = elem;
bitmap |= 1 << i;
}
}
}
return IndexedNode(bitmap, children);
};
/**
Merge two leaf nodes.
@param shift Current shift.
@param h1 Node 1 hash.
@param n1 Node 1.
@param h2 Node 2 hash.
@param n2 Node 2.
*/
var mergeLeaves = function mergeLeaves(shift, h1, n1, h2, n2) {
if (h1 === h2) return Collision(h1, [n2, n1]);
var subH1 = hashFragment(shift, h1);
var subH2 = hashFragment(shift, h2);
return IndexedNode(toBitmap(subH1) | toBitmap(subH2), subH1 === subH2 ? [mergeLeaves(shift + SIZE, h1, n1, h2, n2)] : subH1 < subH2 ? [n1, n2] : [n2, n1]);
};
/**
Update an entry in a collision list.
@param hash Hash of collision.
@param list Collision list.
@param op Update operation.
@param k Key to update.
@param size Size reference
*/
var updateCollisionList = function updateCollisionList(h, list, op, k, size) {
var len = list.length;
for (var i = 0; i < len; ++i) {
var child = list[i];
if (child.key === k) {
var value = child.value;
if (op.__hamt_delete_op) {
--size.value;
return arraySpliceOut(i, list);
}
var _newValue = op.__hamt_set_op ? op.value : op(value);
if (_newValue === value) return list;
return arrayUpdate(i, Leaf(h, k, _newValue), list);
}
}
if (op.__hamt_delete_op) return list;
var newValue = op.__hamt_set_op ? op.value : op();
++size.value;
return arrayUpdate(len, Leaf(h, k, newValue), list);
};
/* Editing
******************************************************************************/
var Leaf__modify = function Leaf__modify(shift, op, h, k, size) {
if (k === this.key) {
if (op.__hamt_delete_op) {
--size.value;
return undefined;
}
var currentValue = this.value;
var _newValue2 = op.__hamt_set_op ? op.value : op(currentValue);
return _newValue2 === currentValue ? this : Leaf(h, k, _newValue2);
}
if (op.__hamt_delete_op) return this;
var newValue = op.__hamt_set_op ? op.value : op();
++size.value;
return mergeLeaves(shift, this.hash, this, h, Leaf(h, k, newValue));
};
var Collision__modify = function Collision__modify(shift, op, h, k, size) {
if (h === this.hash) {
var list = updateCollisionList(this.hash, this.children, op, k, size);
if (list === this.children) return this;
return list.length > 1 ? Collision(this.hash, list) : list[0]; // collapse single element collision list
}
if (op.__hamt_delete_op) return this;
var newValue = op.__hamt_set_op ? op.value : op();
++size.value;
return mergeLeaves(shift, this.hash, this, h, Leaf(h, k, newValue));
};
var IndexedNode__modify = function IndexedNode__modify(shift, op, h, k, size) {
var mask = this.mask;
var children = this.children;
var frag = hashFragment(shift, h);
var bit = toBitmap(frag);
var indx = fromBitmap(mask, bit);
var exists = mask & bit;
if (!exists) {
// add
var _newChild = empty__modify(shift + SIZE, op, h, k, size);
if (!_newChild) return this;
return children.length >= MAX_INDEX_NODE ? expand(frag, _newChild, mask, children) : IndexedNode(mask | bit, arraySpliceIn(indx, _newChild, children));
}
var current = children[indx];
var newChild = current._modify(shift + SIZE, op, h, k, size);
if (current === newChild) return this;
if (!newChild) {
// remove
var bitmap = mask & ~bit;
if (!bitmap) return undefined;
return children.length === 2 && isLeaf(children[indx ^ 1]) ? children[indx ^ 1] // collapse
: IndexedNode(bitmap, arraySpliceOut(indx, children));
}
// modify
return op.__hamt_delete_op && children.length === 1 && isLeaf(newChild) ? newChild // propagate collapse
: IndexedNode(mask, arrayUpdate(indx, newChild, children));
};
var ArrayNode__modify = function ArrayNode__modify(shift, op, h, k, size) {
var count = this.size;
var children = this.children;
var frag = hashFragment(shift, h);
var child = children[frag];
var newChild = child ? child._modify(shift + SIZE, op, h, k, size) : empty__modify(shift + SIZE, op, h, k, size);
if (child === newChild) return this;
if (!child && newChild) {
// add
return ArrayNode(count + 1, arrayUpdate(frag, newChild, children));
}
if (child && !newChild) {
// remove
return count - 1 <= MIN_ARRAY_NODE ? pack(count, frag, children) : ArrayNode(count - 1, arrayUpdate(frag, undefined, children));
}
// modify
return ArrayNode(count, arrayUpdate(frag, newChild, children));
};
var empty__modify = function empty__modify(_, op, h, k, size) {
if (op.__hamt_delete_op) return undefined;
var newValue = op.__hamt_set_op ? op.value : op();
++size.value;
return Leaf(h, k, newValue);
};
/*
******************************************************************************/
function Map(root, size) {
this.root = root;
this.size = size;
};
Map.prototype.__hamt_isMap = true;
Map.prototype.setTree = function (root, size) {
return root === this.root ? this : new Map(root, size);
};
/* Queries
******************************************************************************/
/**
Lookup the value for `key` in `map` using a custom `hash`.
Returns the value or `alt` if none.
*/
var tryGetHash = hamt.tryGetHash = function (alt, hash, key, map) {
if (!map.root) return alt;
var node = map.root;
var shift = 0;
while (true) {
switch (node.type) {
case LEAF:
{
return key === node.key ? node.value : alt;
}
case COLLISION:
{
if (hash === node.hash) {
var children = node.children;
for (var i = 0, len = children.length; i < len; ++i) {
var child = children[i];
if (key === child.key) return child.value;
}
}
return alt;
}
case INDEX:
{
var frag = hashFragment(shift, hash);
var bit = toBitmap(frag);
if (node.mask & bit) {
node = node.children[fromBitmap(node.mask, bit)];
shift += SIZE;
break;
}
return alt;
}
case ARRAY:
{
node = node.children[hashFragment(shift, hash)];
if (node) {
shift += SIZE;
break;
}
return alt;
}
default:
return alt;
}
}
};
Map.prototype.tryGetHash = function (alt, hash, key) {
return tryGetHash(alt, hash, key, this);
};
/**
Lookup the value for `key` in `map` using internal hash function.
@see `tryGetHash`
*/
var tryGet = hamt.tryGet = function (alt, key, map) {
return tryGetHash(alt, hash(key), key, map);
};
Map.prototype.tryGet = function (alt, key) {
return tryGet(alt, key, this);
};
/**
Lookup the value for `key` in `map` using a custom `hash`.
Returns the value or `undefined` if none.
*/
var getHash = hamt.getHash = function (hash, key, map) {
return tryGetHash(undefined, hash, key, map);
};
Map.prototype.getHash = function (hash, key) {
return getHash(hash, key, this);
};
/**
Lookup the value for `key` in `map` using internal hash function.
@see `get`
*/
var get = hamt.get = function (key, map) {
return tryGetHash(undefined, hash(key), key, map);
};
Map.prototype.get = function (key, alt) {
return tryGet(alt, key, this);
};
var nothing = {};
/**
Does an entry exist for `key` in `map`? Uses custom `hash`.
*/
var hasHash = hamt.has = function (hash, key, map) {
return tryGetHash(nothing, hash, key, map) !== nothing;
};
Map.prototype.hasHash = function (hash, key) {
return hasHash(hash, key, this);
};
/**
Does an entry exist for `key` in `map`? Uses internal hash function.
*/
var has = hamt.has = function (key, map) {
return hasHash(hash(key), key, map);
};
Map.prototype.has = function (key) {
return has(key, this);
};
/**
Empty node.
*/
hamt.empty = new Map(undefined, 0);
/**
Is `value` a map?
*/
hamt.isMap = function (value) {
return !!(value && value.__hamt_isMap);
};
/**
Does `map` contain any elements?
*/
hamt.isEmpty = function (map) {
return hamt.isMap(map) && !map.root;
};
Map.prototype.isEmpty = function () {
return hamt.isEmpty(this);
};
/* Updates
******************************************************************************/
/**
Alter the value stored for `key` in `map` using function `f` using
custom hash.
`f` is invoked with the current value for `k` if it exists,
or `defaultValue` if it is specified. Otherwise, `f` is invoked with no arguments
if no such value exists.
`modify` will always either update or insert a value into the map.
Returns a map with the modified value. Does not alter `map`.
*/
var modifyHash = hamt.modifyHash = function (f, hash, key, map) {
var size = { value: map.size };
var newRoot = map.root ? map.root._modify(0, f, hash, key, size) : empty__modify(0, f, hash, key, size);
return map.setTree(newRoot, size.value);
};
Map.prototype.modifyHash = function (hash, key, f) {
return modifyHash(f, hash, key, this);
};
/**
Alter the value stored for `key` in `map` using function `f` using
internal hash function.
@see `modifyHash`
*/
var modify = hamt.modify = function (f, key, map) {
return modifyHash(f, hash(key), key, map);
};
Map.prototype.modify = function (key, f) {
return modify(f, key, this);
};
/**
Same as `modifyHash`, but invokes `f` with `defaultValue` if no entry exists.
@see `modifyHash`
*/
var modifyValueHash = hamt.modifyValueHash = function (f, defaultValue, hash, key, map) {
return modifyHash(defaultValBind(f, defaultValue), hash, key, map);
};
Map.prototype.modifyValueHash = function (hash, key, f, defaultValue) {
return modifyValueHash(f, defaultValue, hash, key, this);
};
/**
@see `modifyValueHash`
*/
var modifyValue = hamt.modifyValue = function (f, defaultValue, key, map) {
return modifyValueHash(f, defaultValue, hash(key), key, map);
};
Map.prototype.modifyValue = function (key, f, defaultValue) {
return modifyValue(f, defaultValue, key, this);
};
/**
Store `value` for `key` in `map` using custom `hash`.
Returns a map with the modified value. Does not alter `map`.
*/
var setHash = hamt.setHash = function (hash, key, value, map) {
return modifyHash({ __hamt_set_op: true, value: value }, hash, key, map);
};
Map.prototype.setHash = function (hash, key, value) {
return setHash(hash, key, value, this);
};
/**
Store `value` for `key` in `map` using internal hash function.
@see `setHash`
*/
var set = hamt.set = function (key, value, map) {
return setHash(hash(key), key, value, map);
};
Map.prototype.set = function (key, value) {
return set(key, value, this);
};
/**
Remove the entry for `key` in `map`.
Returns a map with the value removed. Does not alter `map`.
*/
var del = { __hamt_delete_op: true };
var removeHash = hamt.removeHash = function (hash, key, map) {
return modifyHash(del, hash, key, map);
};
Map.prototype.removeHash = Map.prototype.deleteHash = function (hash, key) {
return removeHash(hash, key, this);
};
/**
Remove the entry for `key` in `map` using internal hash function.
@see `removeHash`
*/
var remove = hamt.remove = function (key, map) {
return removeHash(hash(key), key, map);
};
Map.prototype.remove = Map.prototype.delete = function (key) {
return remove(key, this);
};
/* Traversal
******************************************************************************/
/**
Apply a continuation.
*/
var appk = function appk(k) {
return k && lazyVisitChildren(k.len, k.children, k.i, k.f, k.k);
};
/**
Recursively visit all values stored in an array of nodes lazily.
*/
var lazyVisitChildren = function lazyVisitChildren(len, children, i, f, k) {
while (i < len) {
var child = children[i++];
if (child) return lazyVisit(child, f, { len: len, children: children, i: i, f: f, k: k });
}
return appk(k);
};
/**
Recursively visit all values stored in `node` lazily.
*/
var lazyVisit = function lazyVisit(node, f, k) {
if (node.type === LEAF) return { value: f(node), rest: k };
var children = node.children;
return lazyVisitChildren(children.length, children, 0, f, k);
};
var DONE = { done: true };
/**
Javascript iterator over a map.
*/
function MapIterator(v) {
this.v = v;
};
MapIterator.prototype.next = function () {
if (!this.v) return DONE;
var v0 = this.v;
this.v = appk(v0.rest);
return v0;
};
MapIterator.prototype[Symbol.iterator] = function () {
return this;
};
/**
Lazily visit each value in map with function `f`.
*/
var visit = function visit(map, f) {
return new MapIterator(map.root ? lazyVisit(map.root, f) : undefined);
};
/**
Get a Javascript iterator of `map`.
Iterates over `[key, value]` arrays.
*/
var buildPairs = function buildPairs(x) {
return [x.key, x.value];
};
var entries = hamt.entries = function (map) {
return visit(map, buildPairs);
};
Map.prototype.entries = Map.prototype[Symbol.iterator] = function () {
return entries(this);
};
/**
Get array of all keys in `map`.
Order is not guaranteed.
*/
var buildKeys = function buildKeys(x) {
return x.key;
};
var keys = hamt.keys = function (map) {
return visit(map, buildKeys);
};
Map.prototype.keys = function () {
return keys(this);
};
/**
Get array of all values in `map`.
Order is not guaranteed, duplicates are preserved.
*/
var buildValues = function buildValues(x) {
return x.value;
};
var values = hamt.values = Map.prototype.values = function (map) {
return visit(map, buildValues);
};
Map.prototype.values = function () {
return values(this);
};
/* Fold
******************************************************************************/
/**
Visit every entry in the map, aggregating data.
Order of nodes is not guaranteed.
@param f Function mapping accumulated value, value, and key to new value.
@param z Starting value.
@param m HAMT
*/
var fold = hamt.fold = function (f, z, m) {
var root = m.root;
if (!root) return z;
if (root.type === LEAF) return f(z, root.value, root.key);
for (var toVisit = root; toVisit;) {
var children = toVisit.children;
toVisit = toVisit.next;
for (var i = 0, len = children.length; i < len;) {
var child = children[i++];
if (child) {
if (child.type === LEAF) z = f(z, child.value, child.key);else toVisit = { children: child.children, next: toVisit };
}
}
}
return z;
};
Map.prototype.fold = function (f, z) {
return fold(f, z, this);
};
/**
Visit every entry in the map, aggregating data.
Order of nodes is not guaranteed.
@param f Function invoked with value and key
@param map HAMT
*/
var forEach = hamt.forEach = function (f, map) {
return fold(function (_, value, key) {
return f(value, key, map);
}, null, map);
};
Map.prototype.forEach = function (f) {
return forEach(f, this);
};
/* Aggregate
******************************************************************************/
/**
Get the number of entries in `map`.
*/
var count = hamt.count = function (map) {
return map.size;
};
Map.prototype.count = function () {
return count(this);
};
/* Export
******************************************************************************/
if (typeof module !== 'undefined' && module.exports) {
module.exports = hamt;
} else if (typeof define === 'function' && define.amd) {
define('hamt', [], function () {
return hamt;
});
} else {
undefined.hamt = hamt;
}
//# sourceMappingURL=hamt.js.map