-
Notifications
You must be signed in to change notification settings - Fork 0
/
ST80collections-exp7.js
724 lines (670 loc) · 23.5 KB
/
ST80collections-exp7.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
/*****
This file contains an experimental translation of portions of the Smalltalk-80 Collections
class hierarchy into a dialect of JavaScript that includes features that are under consideration
for inclusion in future editions of the ECMAScript language specification.
The purpose of this translation is to test the expressiveness of the extended language.
***** This Version uses :: instead of <| as the "rototype for" operator
This code has not been tested. It undoubtably has bugs and may have syntax errors.
It is primarily based upon the description of the Collections classes in Chapter 13 of the
Smalltalk blue book (http://stephane.ducasse.free.fr/FreeBooks/BlueBook/ ) with an occasional
peak at the Squeak V1 (http://ftp.squeak.org/1.3/SqueakV1.sources.gz) Collection classes which
are a direct derivative of Xerox Smalltalk-80. The class comments are taken directly from Squeak.
The Xerox and Apple sources for Squeak are licensed under the Apache V2.0 License
(see http://www.squeak.org/SqueakLicense/).
Original material in this file was written by Allen Wirfs-Brock and is
Copyright Mozilla Foundation, 2011
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
license is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
*****/
/*****
The code uses the following proposed ES.next extension:
* modules and modules exports
* the :: operator -- defines the [[Prototype]] of a literal
* the .{ operator -- extends the LHS object with properties from an object literal
* concise method properties in obj lits - foo() {} defines a non-enumerable function data property
* let and const declarations
* super propertry references
* private names created via Name.create
* using [expr] in the propertyname position in an object literal, evaluate the expr to get the name
For these examples :: used with a function expression sets the [[Prototype]] of the object created
as the value of the function's "prototype" property to the value of the "prototype" property of the
the LHS object. This is in addition to setting the [[Prototype]] of the function object itself.
In other words, it builds sets the [[Prototype]] of both the function and of function.prototype to
potentially different values. For example:
function foo() {};
const bar = foo :: function() {};
Object.getPrototypeOf(bar)===foo; //true
Object.getPrototypeOf(bar.prototype)===foo.prototype; //true
This experiment defines "classes" based upon the following code pattern:
const className = superClass :: function(/*constructor parameters * /) {
//constructor body
super.constructor(/*arguments to super constructor * /);
this.{
//per instance property definitions
};
}.prototype.{
//instance properties defined on prototype
}.constructor.{
//class (ie, constructor) properties
};
Private named properties are defined within object literals as follows:
const pname1 = Name.create(); //create a new private name and bind it to a const
const pname2 = Name.create();
let obj = {
regularName: 0,
[pname1]: 1, // a data property with a private name
[pname2]() {reurn this[pname1]} //a method data property with a private name
};
******/
module SmalltalkCollections {
//define a non constructible superclass that provides some Smalltalk-like conventions
const AbstractClass = Function.prototype :: {
subclassResponsibility() {throw new Error(this.name+" did not implemented an abstract method")},
shouldNotImplement() {throw new Error(this.name+" should not implemented by "+this.name)},
name: "AbstractClass",
prototype: Object.prototype ::{
get class() {return this.constructor},
error(message) {throw new Error(message)},
subclassResponsibility() {return this.class.subclassResponsibility()},
shouldNotImplement() {return this.class.shouldNotImplement()},
errorSubscriptBounds(index) {this.error("subscript is out of bounds: "+index)}
}
};
/*-------------------------- Collection --------------------------*/
/* I am the abstract superclass of all classes that represent
a group of elements.
*/
export const Collection = AbstractClass :: function(n) {
}.prototype.{
//adding protocol
add(anObj) {this.subclassResponsibility},
addAll(aCollection) {
const self=this;
aCollection.do(function (each) {self.add(each)});
return this;
},
//removing protocol
removeIfAbsent(anObj,errHandler) {this.subclassResponsibility},
remove(anObj) {
const self=this;
this.removeIfAbsent(anObj,function() {return self.errorNotFound()});
return this;
},
removeAll(aCollection) {
const self=this;
aCollection.do(function(each) {self.remove(each)});
return aCollection;
},
//testing protocol
isEmpty() {return this.size == 0},
includes(anObj) {
try {
this.do(function(each) {if (anObj === each) throw "object found"});
} catch (e) {
if (e==="object found") return true;
else throw e;
};
return false;
},
occurencesOf(anObj) {
let tally = 0;
this.do(function(each) {if (anObj===each) ++tally});
return tally;
},
//accessing
get size() {
let tally = 0;
this.do(function(each) {++tally});
return tally;
},
//enumerating protocol
do(func) {this.subclassResponsibility},
collect(func) {
const newCollection = new this.species;
this.do(function(each) {newCollection.add(func(each))});
return newCollection;
},
detect(pred) {
const self=this;
return this.detectIfNone(pred,function() {return this.errorNotFound()});
},
detectIfNone(pred,exceptFunc) {
try {
this.do(function(each) {if (pred(each)) throw {detected:each}});
} catch (e) {
if (e.hasOwnProperty('detected')) return e.detected;
else throw e;
};
return exceptFunc();
},
injectInto(thisValue,binaryFunc) {
let nextValue = thisValue;
this.do(function(each){nextValue = binaryFunc(nextValue,each)});
return nextValue;
},
reject(pred) {
return this.select(function(element) {return !pred(element)});
},
select(pred) {
const newCollection = new this.species();
this.do(function(each) {if (pred(each)) newCollection.add(each)});
return newCollection;
},
//converting protocol
asBag() {
const aBag = new Bag();
this.do(function(each){aBag.add(each)});
return aBag;
},
asOrderedCollection() {
const anOrderedCollection = new OrderedCollection(this.size);
this.do(function(each){anOrderedCollection.addLast(each)});
return anOrderedCollection;
},
asSet() {
const aSet = new Set();
this.do(function(each){aSet.add(each)});
return aSet;
},
asSortedCollection(sortFunc) {
const aSortedCollection = new SortedCollection(this.size);
if (sortFunc) aSortedCollection.sortFunction = sortFunc;
aSortedCollection.addAll(this);
return aSortedCollection;
},
//printing protocol
printOn(aStream) {
const tooMany = aStream.position + this.maxPrint;
aStream.nextPutAll(this.class.name+'(');
try {
this.do(function(element) {
if (aStream.position > tooMany) {
aStreamNextPutAll('....etc...)');
throw "too long";
};
if (element.printOn) element.printOn(aStream);
else aStream.nextPutAll(element.toString());
});
} catch(e) {
if (e==="too long") return this;
else throw e;
};
aStream.nextPut(')');
return this;
},
storeOn(aStream) {
throw error("the Smalltalk serialization format isn't appropriate for JavaScript");
},
//private protocol for subclasses ("protected" in Java/c++ speak)
maxPrint: 5000, //max size of a printOn string
get species() {return this.constructor},
errorNotFound() {this.error("Object is not in the collection")},
errorNotKeyed() {this.error(this.class.name+"s do not respond to keyed accessing messages")},
errorEmptyCollection() {this.error("this collection is empty")},
emptyCheck() {
if (this.isEmpty()) this.errorEmptyCollection();
}
}.constructor.{
with(...args) {
const newCollection = new this(args.length);
args.forEach(function(element) {newCollection.add(element)});
return newCollection;
},
className: "Collection",
nil: {} //object used to indicate an empty slot in a collection
};
Object.defineProperty(Collection,'nil', {writable: false,configurable:false,enumerable:false});
/*-------------------------- Set --------------------------*/
const setContents = Name.create(), setTally = Name.create();
export const Set = Collection :: function(initialSize=2) {
this.{
[setContents]: new Array(initialSize),
[setTally]: 0
};
}.prototoype.{
//accessing protocol
at(index) {return this.errorNotKeyed()},
atPut(index, anObject) {return this.errorNotKeyed()},
get size() {return this[setTally]},
//testing protocol
includes(anObject) {return this[setContents][this.findElementOrNil(anObject)]!==Collection.nil},
occurrencesOf(anObject) { return this.includes(anObject) ? 1 : 0},
//adding protocol
add(newObject) {
const index = this.findElementOrNil(newObject);
if (this[setContents][index]===Collection.nil) {
this[setContents][index]=newObject;
++this[setTally];
}
return newObject;
},
//removing protocol
removeIfAbsent(oldObject,exceptionBlock) {
const marker={};
let notFound = marker;
const index = this.findIfAbsent(oldObject, function() {notFound=exceptionBlock()});
if (notFound!==marker) return notFound;
this[setContents][index]=Collection.nil;
--this[setTally];
this.fixCollisionsFrom(index);
return oldObject;
},
//enumerating protocol
do(func) {
const contents=this[setContents];
for (let index=0,len=contents.length; index < len;++index) {
const element=contents[index];
if (element!==Collection.nil) func(element);
};
return this;
},
//"protected" internal methods that access bagContents as a hash table
findElementOrNil(anObject) {
throw "need to implement Set.prototype.findElementOrNil";
},
findIfAbsent(anObject,func) {
throw "need to implement Set.prototype.findIfAbsent";
},
fixCollisionsFrom(index) {
throw "need to implement Set.prototype.fixCollisionsFrom";
}
}.constructor.{
className: "Set"
};
/*-------------------------- Bag --------------------------*/
/*I represent an unordered collection of possibly duplicate elements.
I store these elements in a dictionary, tallying up occurrences of
equal objects. Because I store an occurrence only once, my clients
should beware that objects they store will not necessarily be
retrieved such that === is true. If the client cares, a subclass
of me should be created.
*/
const bagContents = Name.create();
export const Bag = Collection :: function() {
this.{
[bagContent]: new Dictionary()
};
}.prototoype.{
//accessing protocol
at(index) {return this.errorNotKeyed()},
atPut(index, anObject) {return this.errorNotKeyed()},
get size() {
let tally = 0;
this[bagContents].do(function(each) {++tally});
return tally;
},
//testing protocol
includes(anObject) {return this[bagContents].includesKey(anObject)},
occurrencesOf(anObject) {
return this.includes(anObject) ? this[bagContents].at(anObject) : 0;
},
//adding protocol
add(newObject) {return this.addWithOccurrences(newObject,1)},
addWithOccurrences(newObject,anInteger) {
this[bagContents].atPut(newObject,Math.round(anInteger)+this.occurrencesOf(newObject));
return newObject;
},
//removing protocol
removeIfAbsent(oldObject,exceptionBlock) {
const count = this.occurrencesOf(oldObject);
switch (count) {
case 0: return exceptionBlock();
case 1:
this[bagContents].removeKey(oldObject);
break;
default:
this[bagContents].atPut(oldObject,count-1);
};
return oldObject;
},
//enumerating protocol
do(func) {
this[bagContents].associationsDo(function(assoc) {
for (let i=0,count=assoc.value; i < count;++i) func(assoc.key);
});
return this;
}
}.constructor.{
className: "Bag"
};
/*-------------------------- Dictionary --------------------------*/
/*I represent a set of elements that can be viewed from one of two
perspectives: a set of associations, or a set of values that are
externally named where the name can be any object that responds
to =. The external name is referred to as the key.
*/
export const Dictionary = Set :: function(...args) {
super.constructor(...args);
}.prototype.{
//accessing protocol
at(key) {
const self=this;
return this.atIfAbsent(key,function(){return self.errorKeyNotFound()}
},
atPut(key, anObject) {
const index = this.findKeyOrNil(key);
const element = this[setContents][index];
if (element===Collection.nil) {
this[setContents][index]= {key: key, value: anObject};
++this[setTally];
} else element.value = anObject;
return anObject;
},
atIfAbsent(key,func) {
const marker={};
let notFound = marker;
const index = this.findKeyIfAbsent(key,function() {notFound=func()});
if (notFound!==marker) return notFound;
return this[setContents][index].value;
},
//testing protocol
includes(anObject) {
/*revert to the implementation in Collection*/
return Collection.prototype.includes.call(this,anObject);
},
//adding protocol
add(anAssociation) {
const index = this.findKeyOrNil(anAssociation.key);
const element = this[setContents][index];
if (element===Collection.nil) {
this[setContents][index]= anAssociation;
++this[setTally];
} else element.value = anAssociation.value;
return anAssociation;
},
//removing protocol
removeIfAbsent(anObject,exceptionBlock) {
this.shouldNotImplement();
},
//enumerating protocol
do(func) {
this.associationsDo(function(assoc) {func(assoc.value)});
return this;
},
associationsDo(func) {
super.do(func); // <---- note super call to different method
return this;
},
collect(func) {
const newCollection = new Bag;
this.do(function(each) {newCollection.add(func(each))});
return newCollection;
},
select(pred) {
const newCollection = new this.species();
this.associationsDo(function(each) {if (pred(each.value)) newCollection.add(each)});
return newCollection;
},
//"protected" internal methods that access bagContents as a hash table
findKeyOrNil(key) {
throw "need to implement Dictionary.prototype.findKeytOrNil";
},
findKeyIfAbsent(key,func) {
throw "need to implement Set.prototype.findKeyIfAbsent";
},
errorKeyNotFound() {this.error("Key not found in "+this.class.name)}
}.constructor.{
className: "Dictionary"
};
/*-------------------------- SequenceableCollection --------------------------*/
/* I am an abstract superclass for collections that have a well-defined order
associated with their elements. Thus each element is externally-named by
integers referred to as indices.
*/
export const SequenceableCollection = Collection :: function(){
super.constructor();
}.prototype.{
//accessing protocol
get size() {return this.subclassResponsibility()},
//removing protocol
removeIfAbsent() {return this.shouldNotImplement()},
//enumerating protocol
do(func) {
let index = 0;
const length = this.size;
while (++indexM<=length) func(this.at(index));
return this;
}
}.constructor.{
name: "SequenceableCollection"
};
/*-------------------------- BasicStorageCollection --------------------------*/
/* This is an implementation class that doesn't exist in the Smalltalk
implementation. It adds a JavasScript Array based backing store to
a collection in order to simulate the array state of a Smalltalk object.
Because Smalltalk arrays 1-origined we bias the size by 1 in order to
preserve the Smalltalk algorithrms */
//Interval private instance variables
const storage=Name.create();
const BasicStorageCollection = SequenceableCollection :: function(elements) {
super.constructor();
this.{
[storage]: new Array(elements+1)
};
}.prototype.{
//"protected" methods for storage access
get basicSize() {return this[storage].length-1},
basicAt(index) {return this[storage][index]},
basicAtPut(index,value) {
this[storage][index] = value;
return value;
}
}.constructor.{
className: "BasicStorageCollection",
};
/*-------------------------- ArrayCollection --------------------------*/
/* I am an abstract collection of elements with a fixed range of integers
(from 1 to n>=1) as external keys.
*/
export const ArrayedCollection = SequenceableCollection :: function(elements=0) {
super.constructor(elements);
}.prototype.{
//accessing protocol
get size() {return this.basicSize},
at(index) {return this.basicAt(Math.floor(index))},
atPut(index,value) {return this.basicAtPut(Math.floor(index),value)},
//adding protocol
add(newObject) {this.shouldNotImplement()},
//protected methods for storage access
}.constructor.{
newWithAll(size,value) {
return (new this(size)).atAllPut(value);
},
with(...args) {
const newCollection = new this(args.length);
let i = 1;
args.forEach(function(element) {newCollection.atPut(i++,element)});
return newCollection;
},
className: "ArrayedCollection",
};
/*-------------------------- Smalltalk Array --------------------------*/
/* I present an ArrayedCollection whose elements are objects.
*/
export const SmalltalkArray = ArrayedCollection :: function(elements=0) {
super.constructor(elements);
}.prototype.{
//converting protocol
asArray() {return this}
}.constructor.{
className: "(Smalltalk)Array"
};
/*-------------------------- Interval --------------------------*/
//Interval private instance variables
const start=Name.create(), stop=Name.create(), step=Name.create();
export const Interval = SequenceableCollection :: function() {
super.constructor();
}.prototype.{
//accessing protocol
get size() {
if (this[step] < 0 )
return this[start] < this[stop] ? 0 : Math.floor((this[stop]-this[start]) / step)+1;
else return this[stop] < this[start] ? 0 : Math.floor((this[stop]-this[start]) / step)+1;
},
at(index) {
if (index >= 1 && index <= this.size) return this.start+(this[step]*(index-1));
else this.errorSubscriptBopunds(index);
},
atPut() {this.error("you cannot store into an Interval")},
//adding protocol
add() {this.error("elements cannot be added to an Interval")},
//removing protocol
remove() {this.error("elements cannot be removed from an Interval")},
//enumerating protocol
do(func) {
let aValue = this[start];
if (this[step]<0) {
while(this[stop]<=aValue) {
func(aValue);
aValue += step;
}
} else {
while(this[stop]>=aValue) {
func(aValue);
aValue += step;
}
};
return this;
},
collect(func) {
const result = new this.species(this.size);
let nextValue = this[start];
let i = 1;
if (this[step]<0) {
while(this[stop]<=nextValue) {
result.atPut(i++,func(nextValue));
aValue += this[step];
}
} else {
while(this[stop]>=nextValue) {
result.atPut(i++,func(nextValue));
aValue += this[step];
}
};
return this;
},
//private
species: SmalltalkArray
}.constructor.{
fromTo(startInteger,stopInteger) {return this.fromToBy(startInteger,stopInteger,1)},
fromToBy(startInteger,stopInteger,stepInteger) {
return (new this).{
[start]: Math.round(startInteger),
[stop]: Math.round(stopInteger),
[step]: Math.round(stepInteger)
}
},
className: "Interval"
};
/*-------------------------- OrderedCollection --------------------------*/
/* I represent a collection of objects ordered by the collector.
*/
//Interval private instance variables
const firstIndex=Name.create(), lastIndex=Name.create();
export const OrderedCollection = BasicStorageCollection :: function(space=10) {
super.constructor(space);
const firstIndx = Math.max(Math.floor(space / 2),1);
this.{
[firstIndex]: firstIndx,
[lastIndex]: Math.max(firstIndx-1,0)
}
}.prototype.{
//accessing protocol
get size() {return this[lastIndex]-this[firstIndex] + 1},
at(anInteger) {
const index = Math.floor(anInteger);
if (index < 1 || anInteger+this[firstIndex]-1 > this[lastIndex])
return this.errorNoSuchElement();
return super.at(index+this[firstIndex]-1);
},
atPut(anInteger,anObject) {
const index = Math.floor(anInteger);
if (anInteger < 1 || anInteger+this[firstIndex]-1 > this[lastIndex])
return this.errorNoSuchElement();
return super.atPut(anInteger+this[firstIndex]-1, anObject);
},
get first() {return this.at(1)},
get last() {return this.at(this.size)},
//adding protocol
add(newObject) {return this.addLast(newObject)},
addFirst(newObject) {
if (this[firstIndex] == 1) this.makeRoomAtFirst();
this.basicAtPut(--this[firstIndex], newObject);
return newObject;
},
addLast(newObject) {
if (this[lastIndex] ==this.basicSize) this.makeRoomAtLast();
this.basicAtPut(++this[lastIndex], newObject);
return newObject;
},
addAll(aCollection) {
aCollection.do(function(element) {this.addLast(element)});
return aCollection;
},
//removing protocol
removeFirst() {
this.emptyCheck();
const firstObj = this.first();
this.basicAtPut(this[firstIndex]++,undefined);
return firstObj;
},
removeLast() {
this.emptyCheck();
const lastObj = this.last();
this.basicAtPut(this[lastIndex]++,undefined);
return lastObj;
},
removeIfAbsent(oldObject, absentBlock) {
let index = this[firstIndex];
while (index <= this[lastIndex]) {
if (oldObject == this.basicAt(index)) {
this.removeIndex(index);
return oldObject;
} else --index;
}
return absentBlock();
},
//enumerating protocol
do(func) {
let index = this[firstIndex];
while (index <= this[lastIndex])
func(this.basicAt(index++));
return this;
},
collect(func) {
const newCollection = new this.species(this.basicSize);
this.do(function(each) {newCollection.add(func(each))});
return newCollection;
},
select(pred) {
const newCollection = new this.species(this.basicSize);
this.do(function(each) {if (pred(each)) newCollection.add(each)});
return newCollection;
},
//private
errorNoSuchElement() {
this.error('attempt to index non-existent element in an ordered collection');
},
emptyCheck() {/*TODO*/},
makeRoomAtLast() {this[storage].length += 1},
makeRoomAtFirst() {
const addedSpace = Math.max(Math.floor(this.basicSize*this.growthFactor),1);
this[storage]=(new Array(addedSpace)).concat(this[storage]);
this[firstIndex] += addedSpace;
this[lastIndex] += addedSpace;
},
get growthFactor() {return 0.20}
}.constructor.{
newFrom(aCollection) {
const newCollection = new this(aCollection.size);
newCollection.addAdd(aCollection);
return newCollection;
},
className: "OrderedCollection"
};
}