-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbasilisk.ts
1453 lines (1227 loc) · 44.1 KB
/
basilisk.ts
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Basilisk is a library for working with immutable data in Javascript or
* related languages.
*/
// internal shims for a few es5 functions which we cannot reasonably expect people to shim.
var freeze = (Object.freeze) ? (obj:any):any => { return Object.freeze(obj) } : (obj:any):any => { return obj; },
hasProp = function (obj, prop):boolean { return Object.hasOwnProperty.call(obj, prop); },
// loosely identify if objects have the same type, mainly used for basilisk-originated objects.
// returns false if both are null or undefined
sameType = function (a:any, b:any):Boolean {
if (a === null || b === null || a === undefined || b === undefined) {
return false;
}
if (a.constructor === undefined || b.constructor === undefined) {
return false;
}
return a.constructor === b.constructor;
};
export interface Struct {
/**
* Given an "example" object, this will create a new object of the same
* 'type', but with the specified name overridden.
*
* @param propName
* @param propValue
*/
with_(propName:string, propValue:any):Struct;
}
export interface Sequence<T> {
// immediately call fn for each item in the sequence.
forEach(fn:(value:T) => any, context:any):void;
forEach(fn:(value:T) => any):void;
}
export module ts {
/**
* A Typescript-specific implementation of Struct, which makes writing new
* Structs easy.
*/
export class Struct {
constructor() {
freeze(this);
}
/**
* Return a new instance of this structure, replacing the named property with
* the provided value.
*
* @param propName the property to replace.
* @param propValue the value to replace.
*/
public with_(propName:string, propValue:any):Struct {
var altered = {},
Maker:{ new(prop:any):Struct } = <{ new(prop:any):Struct }> this.constructor;
for (var prop in this) {
if (hasProp(this, prop)) {
altered[prop] = this[prop];
}
}
altered[propName] = propValue;
return new Maker(altered);
}
}
}
// in ES6 environments, this would be a singleton object.
var StopIteration = StopIteration || "StopIteration";
/**
* Check whether two objects are logically the same. For best effect, either object should
* support a "equals" method.
*
* @param a
* @param b
* @returns {*}
*/
export function equals(a:any, b:any):boolean {
if (a === b) {
return true;
}
// if either is null or undefined at this point, they cannot be the same.
if (a === null || b === null || a === undefined || b === undefined) {
return false;
}
// if a supports equals, try it.
if (typeof a.equals === 'function') {
return a.equals(b);
}
// if b supports equals, try it.
if (typeof b.equals === 'function') {
return b.equals(a);
}
return false;
}
/**
* Given a list of strings, create constructor function which will create instances of the
* named 'class'.
*
* An 'equals' method is added to every struct, which will apply a basilisk-equality check to each
* property in turn to determine equality.
*/
export function makeStruct(baseProps:Array<string>) {
var props = baseProps.slice();
for (var i =0; i<props.length; i++) {
if (props[i].slice(0, 2) === '__') {
throw "Properties of structs cannot start with __, to prevent collision with __proto__ and other core object behaviours.";
} else if (props[i] === 'with_') {
throw "Structs cannot have a 'with_' property, since that collides with the change protocol.";
} else if (props[i] == 'equals') {
throw "Structs cannot have an 'equals' method."
}
}
var Constructor = function (opts:any) {
for (var i=0; i<props.length; i++) {
this[props[i]] = opts[props[i]];
}
freeze(this);
};
for (i=0; i<props.length; i++) {
Constructor.prototype[props[i]] = null;
}
Constructor.prototype.with_ = function (propName:string, propVal:any) {
var altered = {},
found = false;
if (this[propName] === propVal) {
return this;
}
for (var i=0; i<props.length; i++) {
altered[props[i]] = this[props[i]];
if (props[i] === propName) {
found = true;
}
}
if (found && altered[propName] !== propVal) {
altered[propName] = propVal;
return new Constructor(altered);
} else {
return this;
}
};
Constructor.prototype.equals = function (other) {
if (this === other) {
return true;
}
if (other === undefined || other === null) {
return false;
}
// we we
if (sameType(this, other)) {
for (var i=0; i<baseProps.length; i++) {
if (!equals(this[baseProps[i]], other[baseProps[i]])) {
return false;
}
}
// no properties were not equal, thus we must be true.
return true;
} else {
// since we have different prototypes, we must be different objects.
return false;
}
}
return Constructor;
}
/**
* A basic persistent vector class. This is *not* backed by a complex datastructure, and will
* perform very badly for non-trivial data sizes.
*/
export class ArrayVector<T> implements Sequence<T> {
// @private
constructor(ignored:any, ref:Array<T>) {
if (ignored !== undefined) {
throw "TypeError: Vector constructor is private: please use Vector.from()";
}
this.instance = ref;
this.length = this.instance.length;
freeze(this);
}
public static from<T>(sample:ArrayVector<T>):ArrayVector<T>;
public static from<T>(sample:Array<T>):ArrayVector<T>;
public static from<T>(sample:Sequence<T>):ArrayVector<T>;
public static from<T>(sample:any):ArrayVector<T> {
var ref:Array<T>;
if (sample == null) {
ref = [];
} else if (sample instanceof ArrayVector) {
return sample;
} else if (typeof sample.forEach == 'function') {
ref = [];
sample.forEach(function (val:T) {
ref.push(val);
});
}
return new ArrayVector(undefined, ref);
}
private instance:Array<T>;
public length:number;
public append(value:T):ArrayVector<T> {
var copy = this.instance.slice(0);
copy.push(value);
return new ArrayVector<T>(undefined, copy);
}
/**
* Retrieve the object at a particular index. Raises
*/
public get(index:number):T {
if (typeof index !== "number") {
throw "Cannot index a vector with anything other than a number.";
}
if (index < 0) {
index = this.length + index;
}
if (index > this.length || index < 0) {
throw "Out of bounds for Vector";
}
return this.instance[index];
}
/**
* Create a new vector, with the specified index replaced within the object.
*/
public set(index:number, value:T):ArrayVector<T> {
// this will check that we have been indexed by a number.
if (equals(this.get(index), value)) {
return this;
}
if (index < 0) {
index = this.length + index;
}
if (index >= this.length || index < 0) {
throw "Out of bounds";
}
var adjusted = this.instance.slice();
adjusted[index] = value;
return new ArrayVector<T>(undefined, adjusted);
}
public forEach(fn:(value:T, index:number, vect:any) => any, context:any = null):void {
for (var i=0; i < this.instance.length; i++) {
fn.call(context, this.instance[i], i, this);
}
}
public filter(fn:(value:T, index:number, vect:any) => boolean, context:any = null):Sequence<T> {
var replacement = [];
for (var i=0; i < this.instance.length; i++) {
if (fn.call(context, this.instance[i], i, this)) {
replacement.push(this.instance[i]);
}
}
return new ArrayVector<T>(undefined, replacement);
}
public find(fn:(value:T, index:number, vect:any) => boolean, context:any = null):T {
for (var i=0; i < this.instance.length; i++) {
if (fn.call(context, this.instance[i], i, this)) {
return this.instance[i];
}
}
return undefined;
}
public splice(index:number, howMany:number, ... newElements:any[]): {spliced: ArrayVector<T>; removed: ArrayVector<T>} {
var result = [],
removed = [],
i;
if (howMany == 0 && newElements.length == 0) {
return freeze({
spliced: this,
removed: ArrayVector.from([])
});
}
index = v.rangecheck(index, this.length);
for (i = 0; i < index; i++) {
result[i] = this.get(i);
}
newElements.forEach(function(newElement) {
result.push(newElement);
});
for (i = index; i < index + howMany; i++) {
removed.push(this.get(i));
}
for (i = index + howMany; i < this.length; i++) {
result.push(this.get(i));
}
return freeze({spliced: ArrayVector.from(result), removed: ArrayVector.from(removed)});
}
public equals(other:any):boolean {
if (this === other) {
return true;
}
if (other === null || other === undefined) {
return false;
}
if (this.length != other.length) {
return false;
}
// case where it is a vector.
if (sameType(this, other)) {
// must be an Array<T>
for (var i=0; i < this.instance.length; i++) {
if (!equals(other.instance[i], this.instance[i])) {
return false;
}
}
}
return true;
}
}
/**
* A Simple StringMap which can store any object, keyed on a string.
*
* This implementation is convenient when working on the console, but should not be used for more than 40-50 items.
*/
export class SimpleStringMap<T> implements Sequence<T> {
// @private
constructor(ignore:any, inst:any) {
if (ignore !== undefined) {
throw "TypeError: StringMap constructor is private - use .from() to create new instances."
}
this.instance = inst;
freeze(this);
}
public static from<T>(sample:SimpleStringMap<T>);
public static from<T>(sample:any);
public static from<T>(sample:any) {
var inst = {};
if (sample !== null && sample !== undefined) {
if (sample instanceof SimpleStringMap) {
inst = sample.instance;
} else {
for (var k in sample) {
if (hasProp(sample, k)) {
inst[sm.convertKey(k)] = sample[k];
}
}
}
} else {
throw "TypeError: invalid object";
}
return new SimpleStringMap(undefined, inst);
}
private instance:Object;
public get(key:string, default_:T = null):T {
var actualKey:string = sm.convertKey(key);
if (hasProp(this.instance, actualKey)) {
return this.instance[actualKey];
}
return default_;
}
public set(key:string, value:T):SimpleStringMap<T> {
var altered = {};
if (equals(this.get(key), value)) {
return this;
}
for (var prop in this.instance) {
if (hasProp(this.instance, prop)) {
altered[prop] = this.instance[prop];
}
}
altered[sm.convertKey(key)] = value;
// Cheat, knowing that we will use the "instance" property.
return new SimpleStringMap<T>(undefined, altered);
}
public has(key:string):boolean {
return hasProp(this.instance, sm.convertKey(key));
}
public remove(key:string):SimpleStringMap<T> {
var altered = {},
actualKey = sm.convertKey(key);
for (var prop in this.instance) {
if (hasProp(this.instance, prop)) {
if (prop !== actualKey) {
altered[prop] = this.instance[prop];
}
}
}
return new SimpleStringMap<T>(undefined, altered);
}
public forEach(fn:(value:T, key:string, source:any) => any, context:any = undefined):void {
for (var prop in this.instance) {
if (hasProp(this.instance, prop)) {
fn.call(context, this.instance[prop], sm.reverseKey(prop), this);
}
}
}
// Equality for StringMaps is defined as being a StringMap with the same keys, and for each
// key the value must be equals().
public equals(other:any) {
if (this === other) {
return true;
}
if (Object.getPrototypeOf(this) !== Object.getPrototypeOf(other)) {
return false;
}
for (var prop in this.instance) {
if (this.instance.hasOwnProperty(prop)) {
if (!equals(this.instance[prop], other.instance[prop])) {
return false;
}
}
}
for (var prop in other.instance) {
if (other.instance.hasOwnProperty(prop)) {
if (!this.instance.hasOwnProperty(prop)) {
return false;
}
}
}
return true;
}
}
// private utilities for the StringMap implementation.
module sm {
export function convertKey(key:string):string { return key + '___'; }
export function reverseKey(key:string):string { return key.substr(0, key.length - 3); }
}
export class Vector<T> implements Sequence<T> {
constructor(root:Array<any>, shift:number, length:number) {
this.root = root;
this.shift = shift;
this.length = length;
freeze(this);
}
public length:number;
private root:Array<any>;
private shift:number;
public get(index:number):T {
index = v.rangecheck(index, this.length);
var node = this.root;
for (var level = this.shift; level > 0; level -= v.BITS) {
node = node[(index >> level) & v.MASK];
}
return node[(index >> level) & v.MASK];
}
public peek():T {
return this.get(this.length - 1);
}
public set(index:number, value:T):Vector<T> {
index = v.rangecheck(index, this.length);
var root = v.setIndex(this.root, this.shift, index, value);
return new Vector<T>(root, this.shift, this.length);
}
public push(value:T):Vector<T> {
var index = this.length;
var root,
shift = this.shift;
// in the case that the root is full, we add an extra root.
if (this.root.length === v.WIDTH) {
shift = this.shift + v.BITS;
root = v.setIndex([this.root], shift, index, value);
} else {
root = v.setIndex(this.root, shift, index, value);
}
return new Vector<T>(root, shift, this.length + 1);
}
public pop():Vector<T> {
if (this.length === 0) {
throw "OutOfBounds";
} else if (this.length === 1) {
return <Vector<T>> EMPTY_VECTOR;
}
var root = v.pop(this.root, this.shift);
// the initial special cases mean we cannot be completely empty.
// but we want a root with more than one (or we can flatten the tree).
if (this.root.length === 1) {
return new Vector<T>(root[0], this.shift - v.BITS, this.length - 1);
} else {
return new Vector<T>(root, this.shift, this.length - 1);
}
}
public forEach(fn:(value:T, index:number, vect:any) => any, context:any = null):void {
var that = this,
currentIndex = 0,
scan = function (node:Array<any>, level:number):void {
if (level === 0) {
node.forEach(function (item:T, index:number, arr:any[]):void {
fn.call(context, item, currentIndex, that);
currentIndex += 1;
});
} else {
for (var i=0; i<node.length; i++) {
scan(node[i], level - v.BITS);
}
}
};
scan(this.root, this.shift);
}
public equals(other:any):boolean {
if (this === other) {
return true;
}
if (other === null || other === undefined || !(other instanceof Vector)) {
return false;
}
if (this.length !== other.length) {
return false
}
var same = true;
try {
// TODO PERFORMANCE use internal structure to short-circuit much computation.
this.forEach((item:T, index:number) => {
if (!equals(item, other.get(index))) {
same = false;
throw StopIteration;
}
});
} catch (stop) {
if (stop !== StopIteration) {
throw stop;
}
}
return same;
}
public filter(fn:(value:T, index:number, vect:any) => boolean, context:any = undefined):Vector<T> {
// TODO filter should be lazy, and only use a minimum sequence.
var temp = [];
this.forEach((item:T, index:number) => {
if (fn.call(context, item, index, this)) {
temp.push(item);
}
});
if (temp.length === this.length) {
return this;
}
return Vector.from<T>(temp);
}
/**
* Return the first item in the vector for which the function returns true.
*/
public find(fn:(value:T, index:number, vect:any) => boolean, context:any = undefined):T {
var value = undefined,
found = false;
this.forEach((item:T, index:number) => {
if (found) { return; }
if (fn.call(context, item, index, this)) {
value = item;
found = true;
}
});
return value;
}
public findIndex(fn:(value:T, index:number, vect:any) => boolean, context:any = undefined):number {
var value = -1;
this.forEach((item:T, index:number) => {
if (fn.call(context, item, index, this)) {
value = index;
}
});
return value;
}
public splice(index:number, howMany:number, ... newElements:any[]): {spliced: Vector<T>; removed: Vector<T>} {
var result = [],
removed = [],
i;
if (howMany == 0 && newElements.length == 0) {
return freeze({
spliced: this,
removed: Vector.fromArray([])
});
}
index = v.rangecheck(index, this.length);
for (i = 0; i < index; i++) {
result[i] = this.get(i);
}
newElements.forEach(function(newElement) {
result.push(newElement);
});
for (i = index; i < index + howMany; i++) {
removed.push(this.get(i));
}
for (i = index + howMany; i < this.length; i++) {
result.push(this.get(i));
}
return freeze({spliced: Vector.fromArray(result), removed: Vector.fromArray(removed)});
}
// find an item by ===
public indexOf(search:T):number {
var value = -1;
this.forEach((item:T, index:number) => {
if (item === search) {
value = index;
}
});
return value;
}
public map<T2>(mapper:(value:T, index:number, vect:any) => T2, context:any = undefined):Vector<T2> {
var changed:T2[] = [];
this.forEach(function (current:T, index:number, vect:any) {
changed.push(mapper.call(context, current, index, vect));
});
return Vector.from<T2>(changed);
}
public sort(compareFn?:(a:T, b:T) => number):Vector<T> {
var changed = this.toArray().sort(compareFn);
return Vector.from<T>(changed);
}
public toArray():Array<T> {
var arr = [];
this.forEach((item:T) => {
arr.push(item);
});
return arr;
}
// Factory function to create instances from various sources.
static from<T>(obj?:any):Vector<T> {
if (obj === null || obj === undefined) {
return <Vector<T>> EMPTY_VECTOR;
} else if (obj instanceof Vector) {
return obj;
} else if (obj instanceof Array) {
return Vector.fromArray<T>(obj);
} else if (typeof obj.forEach === 'function') {
return Vector.fromArray<T>(obj);
} else {
throw "TypeError: unknown source object for vector: " + obj;
}
}
private static fromArray<T>(obj:Array<T>):Vector<T> {
var result = <Vector<T>> EMPTY_VECTOR;
// TODO this can be optimised pretty easily.
for (var i = 0; i < obj.length; i++) {
result = result.push(obj[i]);
}
return result;
}
private static fromSeq<T>(seq:Sequence<T>):Vector<T> {
var result = <Vector<T>> EMPTY_VECTOR;
// TODO this can be optimised pretty easily.
seq.forEach(function (item:T) {
result = result.push(item);
});
return result;
}
}
var EMPTY_VECTOR = new Vector([], 0, 0);
// Classes required to implement vectors.
module v {
export var BITS = 5,
WIDTH = 1 << BITS,
MASK = WIDTH - 1;
export function rangecheck(index:number, length:number):number {
if (index < 0) {
index += length;
}
if (index < 0 || index >= length) {
throw "OutOfBounds";
}
return index;
}
export function setIndex(node:Array<any>, level:number, index:number, value:any):Array<any> {
var offset = (index >> level) & MASK;
if (level === 0) {
var changed = node.slice(0);
changed[offset] = value;
return changed;
} else {
var changed = node.slice(0);
changed[offset] = setIndex((changed.length == offset) ? [] : changed[offset], level - BITS, index, value);
return changed;
}
}
export function pop(node:Array<any>, level:number):Array<any> {
// if we return null, that means we are empty and should be completely pruned.
// The leaf nodes have slightly simpler behaviour: if this is the last node, return null.
if (level === 0) {
if (node.length === 1) {
return null;
} else {
return node.slice(0, node.length - 1);
}
} else {
// we are always removing the *last* node in the vector, and by extension the last element
// in *this* level.
var offset = node.length - 1,
popped = pop(node[offset], level - BITS),
changed;
if (popped === null) {
if (offset === 0) {
return null;
} else {
// remove the node.
return node.slice(0, node.length - 1);
}
} else {
changed = node.slice(0);
changed[offset] = popped;
return changed;
}
}
}
}
export module hamt {
export var BITS = 5,
WIDTH = 1 << BITS,
MASK = WIDTH - 1;
function mask(shift, value) {
return (value >> shift) & MASK
}
export interface HashFn<K> {
(key:K):number;
}
export interface Node<K, T> {
get(shift:number, hashCode:number, key:K, default_:T):T;
set(shift:number, hashCode:number, key:K, value:T):Node<K, T>;
remove(shift:number, hashCode:number, key:K):Node<K, T>;
forEach(fn:(value:T, key:K, source:any) => any, context:any, source:any):void;
size:number;
}
// A very simple interior node which uses a full array for storin children.
// Uses the fact that javascript arrays are sparse. MEASURE then change if it actually
// makes a space/size/performance difference.
export class Interior<K, T> implements Node<K, T> {
constructor(ignore:any, contents:Array<Node<K, T>>) {
if (ignore !== undefined) {
throw "TypeError: constructor is private - use the .from methods to create new StringMaps";
}
this.contents = contents;
// the size of an interior node is the sum of all of the sizes of its children.
this.size = 0;
for (var i=0; i < contents.length; i++) {
if (contents[i] !== undefined && contents[i] !== null) {
this.size += contents[i].size;
}
}
}
public size:number;
private contents:Array<Node<K, T>>;
get(shift:number, hashCode:number, key:K, default_:T):T {
var index = ((hashCode >> shift) & MASK);
if (this.contents[index] === undefined) {
return default_;
} else {
return this.contents[index].get(shift + BITS, hashCode, key, default_);
}
}
set(shift:number, hashCode:number, key:K, value:T):Node<K, T> {
var index = (hashCode >> shift) & MASK;
if (this.contents[index] === undefined) {
var changed:Array<Node<K, T>> = this.contents.slice(0);
changed[index] = new Leaf(undefined, hashCode, key, value);
return new Interior<K, T>(undefined, changed);
} else {
var newchild = this.contents[index].set(shift + BITS, hashCode, key, value);
if (newchild === this.contents[index]) {
return this;
}
var changed = this.contents.slice(0);
changed[index] = newchild;
return new Interior<K, T>(undefined, changed);
}
}
remove(shift:number, hashCode:number, key:K):Node<K, T> {
var index = mask(shift, hashCode);
if (this.contents[index] === undefined) {
return this;
} else {
var newval = this.contents[index].remove(shift + BITS, hashCode, key),
changed = this.contents.slice(0),
population = 0,
instance:Node<K, T> = undefined;
if (newval === null) {
newval = undefined;
}
changed[index] = newval;
// we now check to see if we have a *single* item (or less)
// since we are using sparse arrays, we have to manually check population.
for (var i=0; i < changed.length; i++) {
if (changed[i] !== undefined) {
population += 1;
instance = changed[i];
}
}
if (population === 0) {
return null;
} else if (population === 1 && (instance instanceof Leaf || instance instanceof Collision)) {
return instance;
} else {
return new Interior<K, T>(undefined, changed);
}
}
}
public forEach(fn:(value:T, key:K, source:any) => any, context:any = undefined, source:any = undefined):void {
var len = this.contents.length;
for (var i=0; i < len; i++) {
if (this.contents[i] !== undefined) {
this.contents[i].forEach(fn, context, source);
}
}
}
}
export class Leaf<K, T> implements Node<K, T> {
constructor(ignore:any, hashCode:number, key:K, value:T) {
if (ignore !== undefined) {
throw "TypeError: constructor is private - use the .from methods to create new StringMaps";
}
this.hashCode = hashCode;
this.key = key;
this.value = value;
this.size = 1;
}
private hashCode:number;
private key:K;
private value:T;
public size:number;
get(shift:number, hashCode:number, key:K, default_:T):T {
if (equals(key, this.key)) {
return this.value;
}
return default_;
}
set(shift:number, hashCode:number, key:K, value:T):Node<K, T> {
if (equals(this.key, key)) {
// replace value.
if (equals(value, this.value)) {
return this;
} else {
// replace ourself
return new Leaf<K, T>(undefined, hashCode, key, value);
}
} else if (hashCode === this.hashCode) {
// collision
return new Collision<K, T>(undefined, this.hashCode, [])
.set(shift, this.hashCode, this.key, this.value)
.set(shift, hashCode, key, value);
} else {
// create a new try, and place our
var newroot = new Interior<K, T>(undefined, []);
return newroot
.set(shift, this.hashCode, this.key, this.value)
.set(shift, hashCode, key, value);
}
}
public remove(shift:number, hashCode:number, key:K):hamt.Node<K, T> {
// just remove ourselves.
return null;
}
public forEach(fn:(value:T, key:K, source:any) => any, context:any = undefined, source:any = undefined):void {
fn.call(context, this.value, this.key, source);
}
}
export class Collision<K, T> implements Node<K, T> {
constructor(ignore:any, hashCode:number, values:Array<any>) {
this.hashCode = hashCode;
this.values = values;
this.size = (values) ? values.length / 2 : 0;
}
private hashCode:number;
// values is an array of [key,value,key,value,key,value...]
private values:Array<any>;
public size:number;
get(shift:number, hashCode:number, key:K, default_:T):T {
// values is a sequence of key, value, key, value objects.
for (var i=0; i < this.values.length / 2; i++) {
if (equals(this.values[2 * i], key)) {