Kernel-Collections.st 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406
  1. Smalltalk createPackage: 'Kernel-Collections'!
  2. Object subclass: #Association
  3. instanceVariableNames: 'key value'
  4. package: 'Kernel-Collections'!
  5. !Association commentStamp!
  6. I represent a pair of associated objects, a key and a value. My instances can serve as entries in a dictionary.
  7. Instances can be created with the class-side method `#key:value:`!
  8. !Association methodsFor: 'accessing'!
  9. key
  10. ^ key
  11. !
  12. key: aKey
  13. key := aKey
  14. !
  15. value
  16. ^ value
  17. !
  18. value: aValue
  19. value := aValue
  20. ! !
  21. !Association methodsFor: 'comparing'!
  22. = anAssociation
  23. ^ self class = anAssociation class and: [
  24. self key = anAssociation key and: [
  25. self value = anAssociation value ]]
  26. ! !
  27. !Association methodsFor: 'printing'!
  28. printOn: aStream
  29. self key printOn: aStream.
  30. aStream nextPutAll: ' -> '.
  31. self value printOn: aStream
  32. ! !
  33. !Association class methodsFor: 'instance creation'!
  34. key: aKey value: aValue
  35. ^ self new
  36. key: aKey;
  37. value: aValue;
  38. yourself
  39. ! !
  40. Object subclass: #BucketStore
  41. instanceVariableNames: 'buckets hashBlock'
  42. package: 'Kernel-Collections'!
  43. !BucketStore commentStamp!
  44. I am an helper class for hash-based stores.
  45. I hold buckets which are selected by a hash, specified using `#hashBlock:`.
  46. The hash can be any object, and
  47. it is used as a JS property (that is, in ES5
  48. its toString() value counts).
  49. ## API
  50. I maintain a list of buckets. Client code can use this API:
  51. - `#bucketOfElement:` (to ask a bucket for element, I can return JS null if n/a)
  52. - `#do:` (to enumerate all elements of all buckets)
  53. - `#removeAll` (to remove all buckets)
  54. Client code itself should add/remove elements
  55. in a bucket. The `nil` object should not be put into any bucket.
  56. Types of buckets are the responsibility of subclasses via `#newBucket`.!
  57. !BucketStore methodsFor: 'accessing'!
  58. bucketOfElement: anObject
  59. <
  60. var hash = self['@hashBlock'](anObject);
  61. if (!!hash) return null;
  62. var buckets = self['@buckets'],
  63. bucket = buckets[hash];
  64. if (!!bucket) { bucket = buckets[hash] = self._newBucket(); }
  65. return bucket;
  66. >
  67. !
  68. hashBlock: aBlock
  69. hashBlock := aBlock
  70. ! !
  71. !BucketStore methodsFor: 'adding/removing'!
  72. removeAll
  73. <self['@buckets'] = Object.create(null);>
  74. ! !
  75. !BucketStore methodsFor: 'enumerating'!
  76. do: aBlock
  77. <
  78. var buckets = self['@buckets'];
  79. var keys = Object.keys(buckets);
  80. for (var i = 0; i < keys.length; ++i) { buckets[keys[i]]._do_(aBlock); }
  81. >
  82. ! !
  83. !BucketStore methodsFor: 'initialization'!
  84. initialize
  85. super initialize.
  86. self removeAll
  87. ! !
  88. !BucketStore methodsFor: 'private'!
  89. newBucket
  90. self subclassResponsibility
  91. ! !
  92. !BucketStore class methodsFor: 'instance creation'!
  93. hashBlock: aBlock
  94. ^ self new
  95. hashBlock: aBlock;
  96. yourself
  97. ! !
  98. BucketStore subclass: #ArrayBucketStore
  99. instanceVariableNames: ''
  100. package: 'Kernel-Collections'!
  101. !ArrayBucketStore commentStamp!
  102. I am a concrete `BucketStore` with buckets being instance of `Array`.!
  103. !ArrayBucketStore methodsFor: 'private'!
  104. newBucket
  105. ^ #()
  106. ! !
  107. Object subclass: #Collection
  108. instanceVariableNames: ''
  109. package: 'Kernel-Collections'!
  110. !Collection commentStamp!
  111. I am the abstract superclass of all classes that represent a group of elements.
  112. I provide a set of useful methods to the Collection hierarchy such as enumerating and converting methods.!
  113. !Collection methodsFor: 'accessing'!
  114. occurrencesOf: anObject
  115. "Answer how many of the receiver's elements are equal to anObject."
  116. | tally |
  117. tally := 0.
  118. self do: [ :each | anObject = each ifTrue: [ tally := tally + 1 ]].
  119. ^ tally
  120. !
  121. size
  122. self subclassResponsibility
  123. ! !
  124. !Collection methodsFor: 'adding/removing'!
  125. add: anObject
  126. self subclassResponsibility
  127. !
  128. addAll: aCollection
  129. aCollection do: [ :each |
  130. self add: each ].
  131. ^ aCollection
  132. !
  133. anyOne
  134. "Answer a representative sample of the receiver. This method can
  135. be helpful when needing to preinfer the nature of the contents of
  136. semi-homogeneous collections."
  137. self ifEmpty: [ self error: 'Collection is empty' ].
  138. self do: [ :each | ^ each ]
  139. !
  140. remove: anObject
  141. ^ self remove: anObject ifAbsent: [ self errorNotFound ]
  142. !
  143. remove: anObject ifAbsent: aBlock
  144. self subclassResponsibility
  145. !
  146. removeAll
  147. self subclassResponsibility
  148. ! !
  149. !Collection methodsFor: 'converting'!
  150. asArray
  151. ^ Array withAll: self
  152. !
  153. asJSON
  154. ^ self asArray collect: [ :each | each asJSON ]
  155. !
  156. asOrderedCollection
  157. ^ self asArray
  158. !
  159. asSet
  160. ^ Set withAll: self
  161. ! !
  162. !Collection methodsFor: 'copying'!
  163. , aCollection
  164. ^ self copy
  165. addAll: aCollection;
  166. yourself
  167. !
  168. copyWith: anObject
  169. ^ self copy add: anObject; yourself
  170. !
  171. copyWithAll: aCollection
  172. ^ self copy addAll: aCollection; yourself
  173. !
  174. copyWithoutAll: aCollection
  175. "Answer a copy of the receiver that does not contain any elements
  176. equal to those in aCollection."
  177. ^ self reject: [ :each | aCollection includes: each ]
  178. ! !
  179. !Collection methodsFor: 'enumerating'!
  180. allSatisfy: aBlock
  181. "Evaluate aBlock with the elements of the receiver.
  182. If aBlock returns false for any element return false.
  183. Otherwise return true."
  184. self do: [ :each | (aBlock value: each) ifFalse: [ ^ false ] ].
  185. ^ true
  186. !
  187. anySatisfy: aBlock
  188. "Evaluate aBlock with the elements of the receiver.
  189. If aBlock returns true for any element return true.
  190. Otherwise return false."
  191. self do: [ :each | (aBlock value: each) ifTrue: [ ^ true ] ].
  192. ^ false
  193. !
  194. collect: aBlock
  195. | stream |
  196. stream := self class new writeStream.
  197. self do: [ :each |
  198. stream nextPut: (aBlock value: each) ].
  199. ^ stream contents
  200. !
  201. detect: aBlock
  202. ^ self detect: aBlock ifNone: [ self errorNotFound ]
  203. !
  204. detect: aBlock ifNone: anotherBlock
  205. self subclassResponsibility
  206. !
  207. do: aBlock
  208. self subclassResponsibility
  209. !
  210. do: aBlock separatedBy: anotherBlock
  211. | actionBeforeElement |
  212. actionBeforeElement := [ actionBeforeElement := anotherBlock ].
  213. self do: [ :each |
  214. actionBeforeElement value.
  215. aBlock value: each ]
  216. !
  217. inject: anObject into: aBlock
  218. | result |
  219. result := anObject.
  220. self do: [ :each |
  221. result := aBlock value: result value: each ].
  222. ^ result
  223. !
  224. intersection: aCollection
  225. "Answer the set theoretic intersection of two collections."
  226. | set outputSet |
  227. set := self asSet.
  228. outputSet := Set new.
  229. aCollection do: [ :each |
  230. ((set includes: each) and: [ (outputSet includes: each) not ])
  231. ifTrue: [
  232. outputSet add: each ]].
  233. ^ self class withAll: outputSet asArray
  234. !
  235. noneSatisfy: aBlock
  236. "Evaluate aBlock with the elements of the receiver.
  237. If aBlock returns false for all elements return true.
  238. Otherwise return false"
  239. self do: [ :item | (aBlock value: item) ifTrue: [ ^ false ] ].
  240. ^ true
  241. !
  242. reject: aBlock
  243. ^ self select: [ :each | (aBlock value: each) = false ]
  244. !
  245. select: aBlock
  246. | stream |
  247. stream := self class new writeStream.
  248. self do: [ :each |
  249. (aBlock value: each) ifTrue: [
  250. stream nextPut: each ] ].
  251. ^ stream contents
  252. !
  253. select: selectBlock thenCollect: collectBlock
  254. | stream |
  255. stream := self class new writeStream.
  256. self do: [ :each |
  257. (selectBlock value: each) ifTrue: [
  258. stream nextPut: (collectBlock value: each) ] ].
  259. ^ stream contents
  260. ! !
  261. !Collection methodsFor: 'error handling'!
  262. errorNotFound
  263. self error: 'Object is not in the collection'
  264. ! !
  265. !Collection methodsFor: 'streaming'!
  266. putOn: aStream
  267. self do: [ :each | each putOn: aStream ]
  268. ! !
  269. !Collection methodsFor: 'testing'!
  270. ifEmpty: aBlock
  271. "Evaluate the given block with the receiver as argument, answering its value if the receiver is empty, otherwise answer the receiver.
  272. Note that the fact that this method returns its argument in case the receiver is not empty allows one to write expressions like the following ones:
  273. self classifyMethodAs:
  274. (myProtocol ifEmpty: ['As yet unclassified'])"
  275. ^ self isEmpty
  276. ifTrue: aBlock
  277. ifFalse: [ self ]
  278. !
  279. ifEmpty: aBlock ifNotEmpty: anotherBlock
  280. ^ self isEmpty
  281. ifTrue: aBlock
  282. ifFalse: [ anotherBlock value: self ]
  283. !
  284. ifNotEmpty: aBlock
  285. ^ self notEmpty
  286. ifTrue: [ aBlock value: self ]
  287. ifFalse: [ self ]
  288. !
  289. ifNotEmpty: aBlock ifEmpty: anotherBlock
  290. ^ self notEmpty
  291. ifTrue: [ aBlock value: self ]
  292. ifFalse: anotherBlock
  293. !
  294. includes: anObject
  295. ^ self anySatisfy: [ :each | each = anObject ]
  296. !
  297. isEmpty
  298. ^ self size = 0
  299. !
  300. notEmpty
  301. ^ self isEmpty not
  302. ! !
  303. !Collection class methodsFor: 'accessing'!
  304. classTag
  305. "Returns a tag or general category for this class.
  306. Typically used to help tools do some reflection.
  307. Helios, for example, uses this to decide what icon the class should display."
  308. ^ 'collection'
  309. ! !
  310. !Collection class methodsFor: 'instance creation'!
  311. new: anInteger
  312. ^ self new
  313. !
  314. with: anObject
  315. ^ self new
  316. add: anObject;
  317. yourself
  318. !
  319. with: anObject with: anotherObject
  320. ^ self new
  321. add: anObject;
  322. add: anotherObject;
  323. yourself
  324. !
  325. with: firstObject with: secondObject with: thirdObject
  326. ^ self new
  327. add: firstObject;
  328. add: secondObject;
  329. add: thirdObject;
  330. yourself
  331. !
  332. withAll: aCollection
  333. ^ self new
  334. addAll: aCollection;
  335. yourself
  336. ! !
  337. Collection subclass: #IndexableCollection
  338. instanceVariableNames: ''
  339. package: 'Kernel-Collections'!
  340. !IndexableCollection commentStamp!
  341. I am a key-value store collection, that is,
  342. I store values under indexes.
  343. As a rule of thumb, if a collection has `#at:` and `#at:put:`,
  344. it is an IndexableCollection.!
  345. !IndexableCollection methodsFor: 'accessing'!
  346. at: anIndex
  347. "Lookup the given index in the receiver.
  348. If it is present, answer the value stored at anIndex.
  349. Otherwise, raise an error."
  350. ^ self at: anIndex ifAbsent: [ self errorNotFound ]
  351. !
  352. at: anIndex ifAbsent: aBlock
  353. "Lookup the given index in the receiver.
  354. If it is present, answer the value stored at anIndex.
  355. Otherwise, answer the value of aBlock."
  356. self subclassResponsibility
  357. !
  358. at: aKey ifAbsentPut: aBlock
  359. ^ self at: aKey ifAbsent: [
  360. self at: aKey put: aBlock value ]
  361. !
  362. at: anIndex ifPresent: aBlock
  363. "Lookup the given index in the receiver.
  364. If it is present, answer the value of evaluating aBlock with the value stored at anIndex.
  365. Otherwise, answer nil."
  366. ^ self at: anIndex ifPresent: aBlock ifAbsent: [ nil ]
  367. !
  368. at: anIndex ifPresent: aBlock ifAbsent: anotherBlock
  369. "Lookup the given index in the receiver.
  370. If it is present, answer the value of evaluating aBlock with the value stored at anIndex.
  371. Otherwise, answer the value of anotherBlock."
  372. self subclassResponsibility
  373. !
  374. at: anIndex put: anObject
  375. "Store anObject under the given index in the receiver."
  376. self subclassResponsibility
  377. !
  378. indexOf: anObject
  379. "Lookup index at which anObject is stored in the receiver.
  380. If not present, raise an error."
  381. ^ self indexOf: anObject ifAbsent: [ self errorNotFound ]
  382. !
  383. indexOf: anObject ifAbsent: aBlock
  384. "Lookup index at which anObject is stored in the receiver.
  385. If not present, return value of executing aBlock."
  386. self subclassResponsibility
  387. ! !
  388. !IndexableCollection methodsFor: 'enumerating'!
  389. with: anotherCollection do: aBlock
  390. "Calls aBlock with every value from self
  391. and with indetically-indexed value from anotherCollection"
  392. self withIndexDo: [ :each :index |
  393. aBlock value: each value: (anotherCollection at: index) ]
  394. !
  395. withIndexDo: aBlock
  396. "Calls aBlock with every value from self
  397. and with its index as the second argument"
  398. self subclassResponsibility
  399. ! !
  400. IndexableCollection subclass: #AssociativeCollection
  401. instanceVariableNames: ''
  402. package: 'Kernel-Collections'!
  403. !AssociativeCollection commentStamp!
  404. I am a base class for object-indexed collections (Dictionary et.al.).!
  405. !AssociativeCollection methodsFor: 'accessing'!
  406. associations
  407. | associations |
  408. associations := #().
  409. self associationsDo: [ :each | associations add: each ].
  410. ^ associations
  411. !
  412. at: aKey ifPresent: aBlock ifAbsent: anotherBlock
  413. "Lookup the given key in the receiver.
  414. If it is present, answer the value of evaluating the oneArgBlock
  415. with the value associated with the key, otherwise answer the value
  416. of absentBlock."
  417. ^ (self includesKey: aKey)
  418. ifTrue: [ aBlock value: (self at: aKey) ]
  419. ifFalse: [ anotherBlock value ]
  420. !
  421. indexOf: anObject ifAbsent: aBlock
  422. ^ self keys
  423. detect: [ :each | (self at: each) = anObject ]
  424. ifNone: aBlock
  425. !
  426. keyAtValue: anObject
  427. ^ self keyAtValue: anObject ifAbsent: [ self errorNotFound ]
  428. !
  429. keyAtValue: anObject ifAbsent: aBlock
  430. ^ self indexOf: anObject ifAbsent: aBlock
  431. !
  432. keys
  433. self subclassResponsibility
  434. !
  435. size
  436. ^ self keys size
  437. !
  438. values
  439. self subclassResponsibility
  440. ! !
  441. !AssociativeCollection methodsFor: 'adding/removing'!
  442. add: anAssociation
  443. self at: anAssociation key put: anAssociation value
  444. !
  445. addAll: anAssociativeCollection
  446. super addAll: anAssociativeCollection associations.
  447. ^ anAssociativeCollection
  448. !
  449. remove: aKey ifAbsent: aBlock
  450. ^ self removeKey: aKey ifAbsent: aBlock
  451. !
  452. removeAll
  453. ^ self keys do: [ :each | self removeKey: each ]
  454. !
  455. removeKey: aKey
  456. ^ self remove: aKey
  457. !
  458. removeKey: aKey ifAbsent: aBlock
  459. self subclassResponsibility
  460. ! !
  461. !AssociativeCollection methodsFor: 'comparing'!
  462. = anAssocitativeCollection
  463. self class = anAssocitativeCollection class ifFalse: [ ^ false ].
  464. self size = anAssocitativeCollection size ifFalse: [ ^ false ].
  465. ^ self associations = anAssocitativeCollection associations
  466. ! !
  467. !AssociativeCollection methodsFor: 'converting'!
  468. asDictionary
  469. ^ Dictionary from: self associations
  470. !
  471. asHashedCollection
  472. ^ HashedCollection from: self associations
  473. !
  474. asJSON
  475. | hash |
  476. hash := HashedCollection new.
  477. self keysAndValuesDo: [ :key :value |
  478. hash at: key put: value asJSON ].
  479. ^ hash
  480. ! !
  481. !AssociativeCollection methodsFor: 'copying'!
  482. deepCopy
  483. | copy |
  484. copy := self class new.
  485. self keysAndValuesDo: [ :key :value |
  486. copy at: key put: value deepCopy ].
  487. ^ copy
  488. !
  489. shallowCopy
  490. | copy |
  491. copy := self class new.
  492. self keysAndValuesDo: [ :key :value |
  493. copy at: key put: value ].
  494. ^ copy
  495. ! !
  496. !AssociativeCollection methodsFor: 'enumerating'!
  497. associationsDo: aBlock
  498. self keysAndValuesDo: [ :key :value |
  499. aBlock value: (Association key: key value: value) ]
  500. !
  501. collect: aBlock
  502. | newDict |
  503. newDict := self class new.
  504. self keysAndValuesDo: [ :key :value |
  505. newDict at: key put: (aBlock value: value) ].
  506. ^ newDict
  507. !
  508. detect: aBlock ifNone: anotherBlock
  509. ^ self values detect: aBlock ifNone: anotherBlock
  510. !
  511. do: aBlock
  512. self valuesDo: aBlock
  513. !
  514. includes: anObject
  515. ^ self values includes: anObject
  516. !
  517. keysAndValuesDo: aBlock
  518. self keysDo: [ :each |
  519. aBlock value: each value: (self at: each) ]
  520. !
  521. keysDo: aBlock
  522. self subclassResponsibility
  523. !
  524. select: aBlock
  525. | newDict |
  526. newDict := self class new.
  527. self keysAndValuesDo: [ :key :value |
  528. (aBlock value: value) ifTrue: [ newDict at: key put: value ]].
  529. ^ newDict
  530. !
  531. valuesDo: aBlock
  532. self subclassResponsibility
  533. !
  534. withIndexDo: aBlock
  535. self keysAndValuesDo: [ :key :value | aBlock value: value value: key ]
  536. ! !
  537. !AssociativeCollection methodsFor: 'printing'!
  538. printOn: aStream
  539. super printOn: aStream.
  540. aStream nextPutAll: ' ('.
  541. self associations
  542. do: [ :each | each printOn: aStream ]
  543. separatedBy: [ aStream nextPutAll: ' , ' ].
  544. aStream nextPutAll: ')'
  545. ! !
  546. !AssociativeCollection methodsFor: 'testing'!
  547. includesKey: aKey
  548. self subclassResponsibility
  549. ! !
  550. !AssociativeCollection class methodsFor: 'instance creation'!
  551. from: aCollection
  552. | newCollection |
  553. newCollection := self new.
  554. aCollection do: [ :each | newCollection add: each ].
  555. ^ newCollection
  556. !
  557. fromPairs: aCollection
  558. "This message is poorly named and has been replaced by #from:"
  559. ^ self from: aCollection
  560. !
  561. newFromPairs: aCollection
  562. "Accept an array of elements where every two elements form an
  563. association - the odd element being the key, and the even element the value."
  564. | newCollection |
  565. aCollection size even ifFalse: [
  566. self error: '#newFromPairs only accepts arrays of an even length' ].
  567. newCollection := self new.
  568. ( 1 to: aCollection size by: 2 ) do: [ :each |
  569. newCollection at: (aCollection at: each) put: (aCollection at: each + 1) ].
  570. ^ newCollection
  571. ! !
  572. AssociativeCollection subclass: #Dictionary
  573. instanceVariableNames: 'keys values'
  574. package: 'Kernel-Collections'!
  575. !Dictionary commentStamp!
  576. I represent a set of elements that can be viewed from one of two perspectives: a set of associations,
  577. or a container of values that are externally named where the name can be any object that responds to `=`.
  578. The external name is referred to as the key.!
  579. !Dictionary methodsFor: 'accessing'!
  580. at: aKey ifAbsent: aBlock
  581. <
  582. var index = self._positionOfKey_(aKey);
  583. return index >>=0 ? self['@values'][index] : aBlock._value();
  584. >
  585. !
  586. at: aKey put: aValue
  587. <
  588. var index = self._positionOfKey_(aKey);
  589. if(index === -1) {
  590. var keys = self['@keys'];
  591. index = keys.length;
  592. keys.push(aKey);
  593. }
  594. return self['@values'][index] = aValue;
  595. >
  596. !
  597. indexOf: anObject ifAbsent: aBlock
  598. | index |
  599. index := values
  600. indexOf: anObject
  601. ifAbsent: [ 0 ].
  602. ^ index = 0
  603. ifTrue: [ aBlock value ]
  604. ifFalse: [ keys at: index ]
  605. !
  606. keys
  607. ^ keys copy
  608. !
  609. values
  610. ^ values
  611. ! !
  612. !Dictionary methodsFor: 'adding/removing'!
  613. removeAll
  614. keys removeAll.
  615. values removeAll
  616. !
  617. removeKey: aKey ifAbsent: aBlock
  618. <
  619. var index = self._positionOfKey_(aKey);
  620. if(index === -1) {
  621. return aBlock._value()
  622. } else {
  623. var keys = self['@keys'], values = self['@values'];
  624. var value = values[index], l = keys.length;
  625. keys[index] = keys[l-1];
  626. keys.pop();
  627. values[index] = values[l-1];
  628. values.pop();
  629. return value;
  630. }
  631. >
  632. ! !
  633. !Dictionary methodsFor: 'enumerating'!
  634. keysAndValuesDo: aBlock
  635. ^ keys with: values do: aBlock
  636. !
  637. keysDo: aBlock
  638. ^ keys do: aBlock
  639. !
  640. valuesDo: aBlock
  641. ^ values do: aBlock
  642. ! !
  643. !Dictionary methodsFor: 'initialization'!
  644. initialize
  645. super initialize.
  646. keys := #().
  647. values := #()
  648. ! !
  649. !Dictionary methodsFor: 'private'!
  650. positionOfKey: anObject
  651. <
  652. var keys = self['@keys'];
  653. for(var i=0;i<keys.length;i++){
  654. if(keys[i].__eq(anObject)) { return i;}
  655. }
  656. return -1;
  657. >
  658. ! !
  659. !Dictionary methodsFor: 'testing'!
  660. includesKey: aKey
  661. < return self._positionOfKey_(aKey) >>= 0; >
  662. ! !
  663. AssociativeCollection subclass: #HashedCollection
  664. instanceVariableNames: ''
  665. package: 'Kernel-Collections'!
  666. !HashedCollection commentStamp!
  667. I am a traditional JavaScript object, or a Smalltalk `Dictionary`.
  668. Unlike a `Dictionary`, I can only have strings as keys.!
  669. !HashedCollection methodsFor: 'accessing'!
  670. at: aKey ifAbsent: aBlock
  671. ^ (self includesKey: aKey)
  672. ifTrue: [ self basicAt: aKey ]
  673. ifFalse: [ aBlock value ]
  674. !
  675. at: aKey put: aValue
  676. ^ self basicAt: aKey put: aValue
  677. !
  678. keys
  679. <return Object.keys(self)>
  680. !
  681. values
  682. <
  683. return self._keys().map(function(key){
  684. return self._at_(key);
  685. });
  686. >
  687. ! !
  688. !HashedCollection methodsFor: 'adding/removing'!
  689. removeKey: aKey ifAbsent: aBlock
  690. ^ self
  691. at: aKey
  692. ifPresent: [ :removed | self basicDelete: aKey. removed ]
  693. ifAbsent: [ aBlock value ]
  694. ! !
  695. !HashedCollection methodsFor: 'enumerating'!
  696. keysDo: aBlock
  697. self keys do: aBlock
  698. !
  699. valuesDo: aBlock
  700. self values do: aBlock
  701. ! !
  702. !HashedCollection methodsFor: 'testing'!
  703. includesKey: aKey
  704. <return self.hasOwnProperty(aKey)>
  705. ! !
  706. IndexableCollection subclass: #SequenceableCollection
  707. instanceVariableNames: ''
  708. package: 'Kernel-Collections'!
  709. !SequenceableCollection commentStamp!
  710. I am an IndexableCollection
  711. with numeric indexes starting with 1.!
  712. !SequenceableCollection methodsFor: 'accessing'!
  713. allButFirst
  714. ^ self copyFrom: 2 to: self size
  715. !
  716. allButLast
  717. ^ self copyFrom: 1 to: self size - 1
  718. !
  719. atRandom
  720. ^ self at: self size atRandom
  721. !
  722. first
  723. ^ self at: 1
  724. !
  725. first: aNumber
  726. "Answer the first `aNumber` elements of the receiver.
  727. Raise an error if there are not enough elements in the receiver."
  728. self size < aNumber ifTrue: [ self error: 'Invalid number of elements' ].
  729. ^ self copyFrom: 1 to: aNumber
  730. !
  731. fourth
  732. ^ self at: 4
  733. !
  734. indexOf: anObject ifAbsent: aBlock
  735. <
  736. self = self._numericallyIndexable();
  737. for(var i=0; i < self.length; i++) {
  738. if($recv(self[i]).__eq(anObject)) {return i+1}
  739. };
  740. return aBlock._value();
  741. >
  742. !
  743. indexOf: anObject startingAt: start
  744. "Answer the index of the first occurence of anElement after start
  745. within the receiver. If the receiver does not contain anElement,
  746. answer 0."
  747. ^ self indexOf: anObject startingAt: start ifAbsent: [ 0 ]
  748. !
  749. indexOf: anObject startingAt: start ifAbsent: aBlock
  750. <
  751. self = self._numericallyIndexable();
  752. for(var i=start - 1; i < self.length; i++){
  753. if($recv(self[i]).__eq(anObject)) {return i+1}
  754. }
  755. return aBlock._value();
  756. >
  757. !
  758. last
  759. ^ self at: self size
  760. !
  761. last: aNumber
  762. "Answer the last aNumber elements of the receiver.
  763. Raise an error if there are not enough elements in the receiver."
  764. self size < aNumber ifTrue: [ self error: 'Invalid number of elements' ].
  765. ^ self copyFrom: self size - aNumber + 1 to: self size
  766. !
  767. second
  768. ^ self at: 2
  769. !
  770. third
  771. ^ self at: 3
  772. ! !
  773. !SequenceableCollection methodsFor: 'adding/removing'!
  774. addLast: anObject
  775. self add: anObject
  776. !
  777. removeLast
  778. ^ self remove: self last
  779. ! !
  780. !SequenceableCollection methodsFor: 'comparing'!
  781. = aCollection
  782. (self class = aCollection class and: [
  783. self size = aCollection size ]) ifFalse: [ ^ false ].
  784. self withIndexDo: [ :each :i |
  785. (aCollection at: i) = each ifFalse: [ ^ false ]].
  786. ^ true
  787. ! !
  788. !SequenceableCollection methodsFor: 'converting'!
  789. reversed
  790. self subclassResponsibility
  791. ! !
  792. !SequenceableCollection methodsFor: 'copying'!
  793. copyFrom: anIndex to: anotherIndex
  794. | range newCollection |
  795. range := anIndex to: anotherIndex.
  796. newCollection := self class new: range size.
  797. range withIndexDo: [ :each :i |
  798. newCollection at: i put: (self at: each) ].
  799. ^ newCollection
  800. !
  801. deepCopy
  802. | newCollection |
  803. newCollection := self class new: self size.
  804. self withIndexDo: [ :each :index |
  805. newCollection at: index put: each deepCopy ].
  806. ^ newCollection
  807. !
  808. shallowCopy
  809. | newCollection |
  810. newCollection := self class new: self size.
  811. self withIndexDo: [ :each :index |
  812. newCollection at: index put: each ].
  813. ^ newCollection
  814. ! !
  815. !SequenceableCollection methodsFor: 'enumerating'!
  816. detect: aBlock ifNone: anotherBlock
  817. <
  818. self = self._numericallyIndexable();
  819. for(var i = 0; i < self.length; i++)
  820. if(aBlock._value_(self[i]))
  821. return self[i];
  822. return anotherBlock._value();
  823. >
  824. !
  825. do: aBlock
  826. <
  827. self = self._numericallyIndexable();
  828. for(var i=0; i < self.length; i++) {
  829. aBlock._value_(self[i]);
  830. }
  831. >
  832. !
  833. with: anotherCollection do: aBlock
  834. <
  835. self = self._numericallyIndexable();
  836. anotherCollection = anotherCollection._numericallyIndexable();
  837. for(var i=0; i<self.length; i++) {
  838. aBlock._value_value_(self[i], anotherCollection[i]);
  839. }
  840. >
  841. !
  842. withIndexDo: aBlock
  843. <
  844. self = self._numericallyIndexable();
  845. for(var i=0; i < self.length; i++) {
  846. aBlock._value_value_(self[i], i+1);
  847. }
  848. >
  849. ! !
  850. !SequenceableCollection methodsFor: 'private'!
  851. numericallyIndexable
  852. "This is an internal converting message.
  853. It answeres a representation of the receiver
  854. that can use foo[i] in JavaScript code.
  855. It fixes IE8, where boxed String is unable
  856. to numerically index its characters,
  857. but primitive string can."
  858. self subclassResponsibility
  859. ! !
  860. !SequenceableCollection methodsFor: 'streaming'!
  861. newStream
  862. ^ self streamClass on: self
  863. !
  864. readStream
  865. "For Pharo compatibility"
  866. ^ self stream
  867. !
  868. stream
  869. ^ self newStream
  870. !
  871. streamClass
  872. ^ self class streamClass
  873. !
  874. writeStream
  875. "For Pharo compatibility"
  876. ^ self stream
  877. ! !
  878. !SequenceableCollection methodsFor: 'testing'!
  879. beginsWith: prefix
  880. self size < prefix size ifTrue: [ ^ false ].
  881. ^ (self first: prefix size) = prefix
  882. !
  883. endsWith: suffix
  884. self size < suffix size ifTrue: [ ^ false ].
  885. ^ (self last: suffix size) = suffix
  886. !
  887. includes: anObject
  888. ^ (self indexOf: anObject ifAbsent: [ nil ]) notNil
  889. ! !
  890. !SequenceableCollection class methodsFor: 'accessing'!
  891. streamClass
  892. ^ Stream
  893. ! !
  894. !SequenceableCollection class methodsFor: 'streaming'!
  895. streamContents: aBlock
  896. | stream |
  897. stream := (self streamClass on: self new).
  898. aBlock value: stream.
  899. ^ stream contents
  900. ! !
  901. SequenceableCollection subclass: #Array
  902. instanceVariableNames: ''
  903. package: 'Kernel-Collections'!
  904. !Array commentStamp!
  905. I represent a collection of objects ordered by the collector. The size of arrays is dynamic.
  906. I am directly mapped to JavaScript Number.
  907. *Note* In Amber, `OrderedCollection` is an alias for `Array`.!
  908. !Array methodsFor: 'accessing'!
  909. at: anIndex ifAbsent: aBlock
  910. <
  911. return anIndex >>= 1 && anIndex <= self.length
  912. ? self[anIndex - 1]
  913. : aBlock._value()
  914. >
  915. !
  916. at: anIndex ifPresent: aBlock ifAbsent: anotherBlock
  917. <
  918. return anIndex >>= 1 && anIndex <= self.length
  919. ? aBlock._value_(self[anIndex - 1])
  920. : anotherBlock._value()
  921. >
  922. !
  923. at: anIndex put: anObject
  924. <return self[anIndex - 1] = anObject>
  925. !
  926. size
  927. <return self.length>
  928. ! !
  929. !Array methodsFor: 'adding/removing'!
  930. add: anObject
  931. <self.push(anObject); return anObject;>
  932. !
  933. addFirst: anObject
  934. <self.unshift(anObject); return anObject;>
  935. !
  936. remove: anObject ifAbsent: aBlock
  937. | index |
  938. index := self indexOf: anObject ifAbsent: [ 0 ].
  939. ^ index = 0
  940. ifFalse: [ self removeIndex: index. anObject ]
  941. ifTrue: [ aBlock value ]
  942. !
  943. removeAll
  944. <self.length = 0>
  945. !
  946. removeFrom: aNumber to: anotherNumber
  947. <self.splice(aNumber -1, anotherNumber - aNumber + 1)>
  948. !
  949. removeIndex: anInteger
  950. <self.splice(anInteger - 1, 1)>
  951. !
  952. removeLast
  953. <return self.pop();>
  954. ! !
  955. !Array methodsFor: 'converting'!
  956. asJavascript
  957. ^ '[', ((self collect: [:each | each asJavascript ]) join: ', '), ']'
  958. !
  959. reversed
  960. <return self._copy().reverse()>
  961. ! !
  962. !Array methodsFor: 'enumerating'!
  963. collect: aBlock
  964. "Optimized version"
  965. <return self.map(function(each) {return aBlock._value_(each)})>
  966. !
  967. join: aString
  968. <return self.join(aString)>
  969. !
  970. select: aBlock
  971. "Optimized version"
  972. <
  973. var result = self.klass._new();
  974. for(var i=0; i<self.length; i++) {
  975. if(aBlock._value_(self[i])) {
  976. result.push(self[i]);
  977. }
  978. }
  979. return result;
  980. >
  981. !
  982. sort
  983. ^ self sort: [ :a :b | a < b ]
  984. !
  985. sort: aBlock
  986. <
  987. return self.sort(function(a, b) {
  988. if(aBlock._value_value_(a,b)) {return -1} else {return 1}
  989. })
  990. >
  991. !
  992. sorted
  993. ^ self copy sort
  994. !
  995. sorted: aBlock
  996. ^ self copy sort: aBlock
  997. ! !
  998. !Array methodsFor: 'printing'!
  999. printOn: aStream
  1000. super printOn: aStream.
  1001. aStream nextPutAll: ' ('.
  1002. self
  1003. do: [ :each | each printOn: aStream ]
  1004. separatedBy: [ aStream nextPutAll: ' ' ].
  1005. aStream nextPutAll: ')'
  1006. ! !
  1007. !Array methodsFor: 'private'!
  1008. numericallyIndexable
  1009. ^ self
  1010. ! !
  1011. !Array class methodsFor: 'instance creation'!
  1012. new: anInteger
  1013. <return new Array(anInteger)>
  1014. !
  1015. with: anObject
  1016. ^ (self new: 1)
  1017. at: 1 put: anObject;
  1018. yourself
  1019. !
  1020. with: anObject with: anObject2
  1021. ^ (self new: 2)
  1022. at: 1 put: anObject;
  1023. at: 2 put: anObject2;
  1024. yourself
  1025. !
  1026. with: anObject with: anObject2 with: anObject3
  1027. ^ (self new: 3)
  1028. at: 1 put: anObject;
  1029. at: 2 put: anObject2;
  1030. at: 3 put: anObject3;
  1031. yourself
  1032. !
  1033. withAll: aCollection
  1034. | instance index |
  1035. index := 1.
  1036. instance := self new: aCollection size.
  1037. aCollection do: [ :each |
  1038. instance at: index put: each.
  1039. index := index + 1 ].
  1040. ^ instance
  1041. ! !
  1042. SequenceableCollection subclass: #CharacterArray
  1043. instanceVariableNames: ''
  1044. package: 'Kernel-Collections'!
  1045. !CharacterArray commentStamp!
  1046. I am the abstract superclass of string-like collections.!
  1047. !CharacterArray methodsFor: 'accessing'!
  1048. at: anIndex put: anObject
  1049. self errorReadOnly
  1050. ! !
  1051. !CharacterArray methodsFor: 'adding/removing'!
  1052. add: anObject
  1053. self errorReadOnly
  1054. !
  1055. remove: anObject
  1056. self errorReadOnly
  1057. ! !
  1058. !CharacterArray methodsFor: 'converting'!
  1059. asLowercase
  1060. ^ self class fromString: self asString asLowercase
  1061. !
  1062. asNumber
  1063. ^ self asString asNumber
  1064. !
  1065. asString
  1066. ^ self subclassResponsibility
  1067. !
  1068. asSymbol
  1069. ^ self asString
  1070. !
  1071. asUppercase
  1072. ^ self class fromString: self asString asUppercase
  1073. ! !
  1074. !CharacterArray methodsFor: 'copying'!
  1075. , aString
  1076. ^ self asString, aString asString
  1077. ! !
  1078. !CharacterArray methodsFor: 'error handling'!
  1079. errorReadOnly
  1080. self error: 'Object is read-only'
  1081. ! !
  1082. !CharacterArray methodsFor: 'printing'!
  1083. printOn: aStream
  1084. self asString printOn: aStream
  1085. ! !
  1086. !CharacterArray methodsFor: 'streaming'!
  1087. putOn: aStream
  1088. aStream nextPutString: self
  1089. ! !
  1090. !CharacterArray class methodsFor: 'instance creation'!
  1091. fromString: aString
  1092. self subclassResponsibility
  1093. ! !
  1094. CharacterArray subclass: #String
  1095. instanceVariableNames: ''
  1096. package: 'Kernel-Collections'!
  1097. !String commentStamp!
  1098. I am an indexed collection of Characters. Unlike most Smalltalk dialects, Amber doesn't provide the Character class. Instead, elements of a String are single character strings.
  1099. String inherits many useful methods from its hierarchy, such as
  1100. `Collection >> #,`!
  1101. !String methodsFor: 'accessing'!
  1102. asciiValue
  1103. <return self.charCodeAt(0);>
  1104. !
  1105. at: anIndex ifAbsent: aBlock
  1106. <return String(self)[anIndex - 1] || aBlock._value()>
  1107. !
  1108. at: anIndex ifPresent: aBlock ifAbsent: anotherBlock
  1109. <
  1110. var result = String(self)[anIndex - 1];
  1111. return result ? aBlock._value_(result) : anotherBlock._value();
  1112. >
  1113. !
  1114. charCodeAt: anInteger
  1115. <return self.charCodeAt(anInteger - 1)>
  1116. !
  1117. identityHash
  1118. ^ self, 's'
  1119. !
  1120. size
  1121. <return self.length>
  1122. ! !
  1123. !String methodsFor: 'comparing'!
  1124. < aString
  1125. <return String(self) < aString._asString()>
  1126. !
  1127. <= aString
  1128. <return String(self) <= aString._asString()>
  1129. !
  1130. = aString
  1131. <
  1132. return aString !!= null &&
  1133. typeof aString._isString === "function" &&
  1134. aString._isString() &&
  1135. String(self) === String(aString)
  1136. >
  1137. !
  1138. == aString
  1139. ^ self = aString
  1140. !
  1141. > aString
  1142. <return String(self) >> aString._asString()>
  1143. !
  1144. >= aString
  1145. <return String(self) >>= aString._asString()>
  1146. ! !
  1147. !String methodsFor: 'converting'!
  1148. asJSON
  1149. ^ self
  1150. !
  1151. asJavaScriptMethodName
  1152. <return $core.st2js(self)>
  1153. !
  1154. asJavascript
  1155. <
  1156. if(self.search(/^[a-zA-Z0-9_:.$ ]*$/) == -1)
  1157. return "\"" + self.replace(/[\x00-\x1f"\\\x7f-\x9f]/g, function(ch){var c=ch.charCodeAt(0);return "\\x"+("0"+c.toString(16)).slice(-2)}) + "\"";
  1158. else
  1159. return "\"" + self + "\"";
  1160. >
  1161. !
  1162. asLowercase
  1163. <return self.toLowerCase()>
  1164. !
  1165. asMutator
  1166. "Answer a setter selector. For example,
  1167. #name asMutator returns #name:"
  1168. self last = ':' ifFalse: [ ^ self, ':' ].
  1169. ^ self
  1170. !
  1171. asNumber
  1172. <return Number(self)>
  1173. !
  1174. asRegexp
  1175. ^ RegularExpression fromString: self
  1176. !
  1177. asString
  1178. ^ self
  1179. !
  1180. asSymbol
  1181. ^ self
  1182. !
  1183. asUppercase
  1184. <return self.toUpperCase()>
  1185. !
  1186. capitalized
  1187. ^ self isEmpty
  1188. ifTrue: [ self ]
  1189. ifFalse: [ self first asUppercase, self allButFirst ]
  1190. !
  1191. crlfSanitized
  1192. ^ self lines join: String lf
  1193. !
  1194. escaped
  1195. <return escape(self)>
  1196. !
  1197. reversed
  1198. <return self.split("").reverse().join("")>
  1199. !
  1200. unescaped
  1201. <return unescape(self)>
  1202. !
  1203. uriComponentDecoded
  1204. <return decodeURIComponent(self)>
  1205. !
  1206. uriComponentEncoded
  1207. <return encodeURIComponent(self)>
  1208. !
  1209. uriDecoded
  1210. <return decodeURI(self)>
  1211. !
  1212. uriEncoded
  1213. <return encodeURI(self)>
  1214. ! !
  1215. !String methodsFor: 'copying'!
  1216. , aString
  1217. <return String(self) + aString>
  1218. !
  1219. copyFrom: anIndex to: anotherIndex
  1220. <return self.substring(anIndex - 1, anotherIndex)>
  1221. !
  1222. deepCopy
  1223. ^ self shallowCopy
  1224. !
  1225. shallowCopy
  1226. ^ self class fromString: self
  1227. ! !
  1228. !String methodsFor: 'evaluating'!
  1229. value: anObject
  1230. ^ anObject perform: self
  1231. ! !
  1232. !String methodsFor: 'printing'!
  1233. printNl
  1234. <console.log(self)>
  1235. !
  1236. printOn: aStream
  1237. aStream
  1238. nextPutAll: '''';
  1239. nextPutAll: self;
  1240. nextPutAll: ''''
  1241. ! !
  1242. !String methodsFor: 'private'!
  1243. numericallyIndexable
  1244. <return String(self)>
  1245. ! !
  1246. !String methodsFor: 'regular expressions'!
  1247. match: aRegexp
  1248. <return self.search(aRegexp) !!= -1>
  1249. !
  1250. matchesOf: aRegularExpression
  1251. <return self.match(aRegularExpression)>
  1252. !
  1253. replace: aString with: anotherString
  1254. ^ self replaceRegexp: (RegularExpression fromString: aString flag: 'g') with: anotherString
  1255. !
  1256. replaceRegexp: aRegexp with: aString
  1257. <return self.replace(aRegexp, aString)>
  1258. !
  1259. trimBoth
  1260. ^ self trimBoth: '\s'
  1261. !
  1262. trimBoth: separators
  1263. ^ (self trimLeft: separators) trimRight: separators
  1264. !
  1265. trimLeft
  1266. ^ self trimLeft: '\s'
  1267. !
  1268. trimLeft: separators
  1269. ^ self replaceRegexp: (RegularExpression fromString: '^[', separators, ']+' flag: 'g') with: ''
  1270. !
  1271. trimRight
  1272. ^ self trimRight: '\s'
  1273. !
  1274. trimRight: separators
  1275. ^ self replaceRegexp: (RegularExpression fromString: '[', separators, ']+$' flag: 'g') with: ''
  1276. ! !
  1277. !String methodsFor: 'split join'!
  1278. join: aCollection
  1279. ^ String
  1280. streamContents: [ :stream | aCollection
  1281. do: [ :each | stream nextPutAll: each asString ]
  1282. separatedBy: [ stream nextPutAll: self ]]
  1283. !
  1284. lineIndicesDo: aBlock
  1285. "execute aBlock with 3 arguments for each line:
  1286. - start index of line
  1287. - end index of line without line delimiter
  1288. - end index of line including line delimiter(s) CR, LF or CRLF"
  1289. | cr lf start sz nextLF nextCR |
  1290. start := 1.
  1291. sz := self size.
  1292. cr := String cr.
  1293. nextCR := self indexOf: cr startingAt: 1.
  1294. lf := String lf.
  1295. nextLF := self indexOf: lf startingAt: 1.
  1296. [ start <= sz ] whileTrue: [
  1297. (nextLF = 0 and: [ nextCR = 0 ])
  1298. ifTrue: [ "No more CR, nor LF, the string is over"
  1299. aBlock value: start value: sz value: sz.
  1300. ^ self ].
  1301. (nextCR = 0 or: [ 0 < nextLF and: [ nextLF < nextCR ] ])
  1302. ifTrue: [ "Found a LF"
  1303. aBlock value: start value: nextLF - 1 value: nextLF.
  1304. start := 1 + nextLF.
  1305. nextLF := self indexOf: lf startingAt: start ]
  1306. ifFalse: [ 1 + nextCR = nextLF
  1307. ifTrue: [ "Found a CR-LF pair"
  1308. aBlock value: start value: nextCR - 1 value: nextLF.
  1309. start := 1 + nextLF.
  1310. nextCR := self indexOf: cr startingAt: start.
  1311. nextLF := self indexOf: lf startingAt: start ]
  1312. ifFalse: [ "Found a CR"
  1313. aBlock value: start value: nextCR - 1 value: nextCR.
  1314. start := 1 + nextCR.
  1315. nextCR := self indexOf: cr startingAt: start ] ]]
  1316. !
  1317. lineNumber: anIndex
  1318. "Answer a string containing the characters in the given line number."
  1319. | lineCount |
  1320. lineCount := 0.
  1321. self lineIndicesDo: [ :start :endWithoutDelimiters :end |
  1322. (lineCount := lineCount + 1) = anIndex ifTrue: [ ^ self copyFrom: start to: endWithoutDelimiters ]].
  1323. ^ nil
  1324. !
  1325. lines
  1326. "Answer an array of lines composing this receiver without the line ending delimiters."
  1327. | lines |
  1328. lines := Array new.
  1329. self linesDo: [ :aLine | lines add: aLine ].
  1330. ^ lines
  1331. !
  1332. linesDo: aBlock
  1333. "Execute aBlock with each line in this string. The terminating line
  1334. delimiters CR, LF or CRLF pairs are not included in what is passed to aBlock"
  1335. self lineIndicesDo: [ :start :endWithoutDelimiters :end |
  1336. aBlock value: (self copyFrom: start to: endWithoutDelimiters) ]
  1337. !
  1338. subStrings: aString
  1339. ^ self tokenize: aString
  1340. !
  1341. tokenize: aString
  1342. <return self.split(aString)>
  1343. ! !
  1344. !String methodsFor: 'testing'!
  1345. includesSubString: subString
  1346. <return self.indexOf(subString) !!= -1>
  1347. !
  1348. isCapitalized
  1349. ^ self first asUppercase == self first
  1350. !
  1351. isImmutable
  1352. ^ true
  1353. !
  1354. isString
  1355. ^ true
  1356. !
  1357. isVowel
  1358. "Answer true if the receiver is a one character string containing a voyel"
  1359. ^ self size = 1 and: [ 'aeiou' includes: self asLowercase ]
  1360. ! !
  1361. !String class methodsFor: 'accessing'!
  1362. cr
  1363. <return '\r'>
  1364. !
  1365. crlf
  1366. <return '\r\n'>
  1367. !
  1368. esc
  1369. ^ self fromCharCode: 27
  1370. !
  1371. lf
  1372. <return '\n'>
  1373. !
  1374. space
  1375. <return ' '>
  1376. !
  1377. streamClass
  1378. ^ StringStream
  1379. !
  1380. tab
  1381. <return '\t'>
  1382. ! !
  1383. !String class methodsFor: 'instance creation'!
  1384. fromCharCode: anInteger
  1385. <return String.fromCharCode(anInteger)>
  1386. !
  1387. fromString: aString
  1388. <return String(aString)>
  1389. !
  1390. value: aUTFCharCode
  1391. <return String.fromCharCode(aUTFCharCode);>
  1392. ! !
  1393. !String class methodsFor: 'random'!
  1394. random
  1395. "Returns random alphanumeric string beginning with letter"
  1396. <return (Math.random()*(22/32)+(10/32)).toString(32).slice(2);>
  1397. !
  1398. randomNotIn: aString
  1399. | result |
  1400. [ result := self random. aString includesSubString: result ] whileTrue.
  1401. ^ result
  1402. ! !
  1403. Collection subclass: #Set
  1404. instanceVariableNames: 'defaultBucket slowBucketStores fastBuckets size'
  1405. package: 'Kernel-Collections'!
  1406. !Set commentStamp!
  1407. I represent an unordered set of objects without duplicates.
  1408. ## Implementation notes
  1409. I put elements into different stores based on their type.
  1410. The goal is to store some elements into native JS object property names to be fast.
  1411. If an unboxed element has typeof 'string', 'boolean' or 'number', or an element is nil, null or undefined,
  1412. I store it as a property name in an empty (== Object.create(null)) JS object, different for each type
  1413. (for simplicity, nil/null/undefined is treated as one and included with the two booleans).
  1414. If element happen to be an object, I try to store them in `ArrayBucketStore`. I have two of them by default,
  1415. one hashed using the Smalltalk class name, the other one using the JS constructor name. It is possible to have more or less
  1416. instances of `ArrayBucketStores`, see `#initializeSlowBucketStores`.
  1417. As a last resort, if none of the `ArrayBucketStore` instances can find a suitable bucket, the `defaultBucket` is used,
  1418. which is an `Array`.!
  1419. !Set methodsFor: 'accessing'!
  1420. size
  1421. ^ size
  1422. ! !
  1423. !Set methodsFor: 'adding/removing'!
  1424. add: anObject
  1425. | bucket |
  1426. bucket := self bucketsOfElement: anObject.
  1427. ^ bucket second
  1428. ifNil: [
  1429. | object slowBucket |
  1430. object := bucket first.
  1431. slowBucket := bucket third.
  1432. slowBucket
  1433. indexOf: object
  1434. ifAbsent: [
  1435. slowBucket add: object.
  1436. size := size + 1 ].
  1437. object ]
  1438. ifNotNil: [ :primitiveBucket |
  1439. self
  1440. add: bucket first
  1441. in: primitiveBucket ]
  1442. !
  1443. remove: anObject ifAbsent: aBlock
  1444. | bucket |
  1445. bucket := self bucketsOfElement: anObject.
  1446. ^ bucket second
  1447. ifNil: [ bucket third remove: bucket first ifAbsent: [ ^aBlock value ]. size := size - 1 ]
  1448. ifNotNil: [ :primitiveBucket | self remove: bucket first in: primitiveBucket ]
  1449. !
  1450. removeAll
  1451. <
  1452. self['@fastBuckets'] = {
  1453. 'boolean': { store: Object.create(null), fn: function (x) { return {'true': true, 'false': false, 'null': null}[x]; } },
  1454. 'number': { store: Object.create(null), fn: Number },
  1455. 'string': { store: Object.create(null) }
  1456. };
  1457. self['@slowBucketStores'].forEach(function (x) { x._removeAll(); });
  1458. self['@defaultBucket']._removeAll();
  1459. self['@size'] = 0;
  1460. >
  1461. ! !
  1462. !Set methodsFor: 'comparing'!
  1463. = aCollection
  1464. self class = aCollection class ifFalse: [ ^ false ].
  1465. self size = aCollection size ifFalse: [ ^ false ].
  1466. self do: [ :each | (aCollection includes: each) ifFalse: [ ^ false ] ].
  1467. ^ true
  1468. ! !
  1469. !Set methodsFor: 'enumerating'!
  1470. collect: aBlock
  1471. | collection |
  1472. collection := self class new.
  1473. self do: [ :each | collection add: (aBlock value: each) ].
  1474. ^ collection
  1475. !
  1476. detect: aBlock ifNone: anotherBlock
  1477. self do: [ :each | (aBlock value: each) ifTrue: [ ^each ] ].
  1478. ^ anotherBlock value
  1479. !
  1480. do: aBlock
  1481. <
  1482. var el, keys, i;
  1483. el = self['@fastBuckets'];
  1484. keys = Object.keys(el);
  1485. for (i = 0; i < keys.length; ++i) {
  1486. var fastBucket = el[keys[i]], fn = fastBucket.fn, store = Object.keys(fastBucket.store);
  1487. if (fn) { for (var j = 0; j < store.length; ++j) { aBlock._value_(fn(store[j])); } }
  1488. else { store._do_(aBlock); }
  1489. }
  1490. el = self['@slowBucketStores'];
  1491. for (i = 0; i < el.length; ++i) { el[i]._do_(aBlock); }
  1492. self['@defaultBucket']._do_(aBlock);
  1493. >
  1494. !
  1495. select: aBlock
  1496. | collection |
  1497. collection := self class new.
  1498. self do: [ :each |
  1499. (aBlock value: each) ifTrue: [
  1500. collection add: each ] ].
  1501. ^ collection
  1502. ! !
  1503. !Set methodsFor: 'initialization'!
  1504. initialize
  1505. super initialize.
  1506. defaultBucket := #().
  1507. self
  1508. initializeSlowBucketStores;
  1509. removeAll
  1510. !
  1511. initializeSlowBucketStores
  1512. slowBucketStores := {
  1513. ArrayBucketStore hashBlock: [ :x | self classNameOf: x ].
  1514. ArrayBucketStore hashBlock: [ :x | self jsConstructorNameOf: x ]
  1515. }
  1516. ! !
  1517. !Set methodsFor: 'printing'!
  1518. printOn: aStream
  1519. super printOn: aStream.
  1520. aStream nextPutAll: ' ('.
  1521. self
  1522. do: [ :each | each printOn: aStream ]
  1523. separatedBy: [ aStream nextPutAll: ' ' ].
  1524. aStream nextPutAll: ')'
  1525. ! !
  1526. !Set methodsFor: 'private'!
  1527. add: anObject in: anotherObject
  1528. <
  1529. if (anObject in anotherObject.store) { return false; }
  1530. self['@size']++;
  1531. return anotherObject.store[anObject] = true;
  1532. >
  1533. !
  1534. bucketsOfElement: anObject
  1535. "Find the appropriate bucket for `anObject`.
  1536. For optimization purposes, directly answer an array with:
  1537. - the object to be store
  1538. - the primitive bucket
  1539. - the slow bucket"
  1540. <
  1541. var type, bucket, prim = anObject == null ? (anObject = nil) : anObject.valueOf();
  1542. if ((type = typeof prim) === "object") {
  1543. if (anObject !!== nil) {
  1544. bucket = null;
  1545. self['@slowBucketStores'].some(function (store) {
  1546. return bucket = store._bucketOfElement_(anObject);
  1547. });
  1548. return [ anObject, null, bucket || self['@defaultBucket'] ];
  1549. }
  1550. // include nil to well-known objects under 'boolean' fastBucket
  1551. prim = null;
  1552. type = 'boolean';
  1553. }
  1554. return [ prim, self['@fastBuckets'][type] ];
  1555. >
  1556. !
  1557. classNameOf: anObject
  1558. "Answer the class name of `anObject`, or `undefined`
  1559. if `anObject` is not an Smalltalk object"
  1560. <return anObject.klass && anObject.klass.className>
  1561. !
  1562. includes: anObject in: anotherObject
  1563. <return anObject in anotherObject.store>
  1564. !
  1565. jsConstructorNameOf: anObject
  1566. <return anObject.constructor && anObject.constructor.name>
  1567. !
  1568. remove: anObject in: anotherObject
  1569. <if (delete anotherObject.store[anObject]) self['@size']-->
  1570. ! !
  1571. !Set methodsFor: 'testing'!
  1572. includes: anObject
  1573. | bucket |
  1574. bucket := self bucketsOfElement: anObject.
  1575. ^ bucket second
  1576. ifNil: [ bucket third includes: bucket first ]
  1577. ifNotNil: [ :primitiveBucket | self includes: bucket first in: primitiveBucket ]
  1578. ! !
  1579. Object subclass: #ProtoStream
  1580. instanceVariableNames: ''
  1581. package: 'Kernel-Collections'!
  1582. !ProtoStream commentStamp!
  1583. I am the abstract base for different accessor for a sequence of objects. This sequence is referred to as my "contents".
  1584. My instances are read/write streams modifying the contents.!
  1585. !ProtoStream methodsFor: 'accessing'!
  1586. contents
  1587. self subclassResponsibility
  1588. ! !
  1589. !ProtoStream methodsFor: 'actions'!
  1590. reset
  1591. self subclassResponsibility
  1592. !
  1593. resetContents
  1594. self subclassResponsibility
  1595. ! !
  1596. !ProtoStream methodsFor: 'enumerating'!
  1597. do: aBlock
  1598. [ self atEnd ] whileFalse: [ aBlock value: self next ]
  1599. ! !
  1600. !ProtoStream methodsFor: 'positioning'!
  1601. setToEnd
  1602. self subclassResponsibility
  1603. !
  1604. setToStart
  1605. self reset
  1606. ! !
  1607. !ProtoStream methodsFor: 'reading'!
  1608. next
  1609. ^ self atEnd
  1610. ifTrue: [ nil ]
  1611. ifFalse: [ self subclassResponsibility ]
  1612. !
  1613. peek
  1614. ^ self atEnd
  1615. ifTrue: [ nil ]
  1616. ifFalse: [ self subclassResponsibility ]
  1617. ! !
  1618. !ProtoStream methodsFor: 'testing'!
  1619. atEnd
  1620. self subclassResponsibility
  1621. !
  1622. atStart
  1623. self subclassResponsibility
  1624. !
  1625. isEmpty
  1626. ^ self atStart and: [ self atEnd ]
  1627. ! !
  1628. !ProtoStream methodsFor: 'writing'!
  1629. << anObject
  1630. self write: anObject
  1631. !
  1632. nextPut: anObject
  1633. self subclassResponsibility
  1634. !
  1635. nextPutAll: aCollection
  1636. aCollection do: [ :each |
  1637. self nextPut: each ]
  1638. !
  1639. nextPutString: aString
  1640. self nextPut: aString
  1641. !
  1642. write: anObject
  1643. anObject putOn: self
  1644. ! !
  1645. !ProtoStream class methodsFor: 'instance creation'!
  1646. on: aCollection
  1647. ^ self new
  1648. setCollection: aCollection;
  1649. setStreamSize: aCollection size;
  1650. yourself
  1651. ! !
  1652. ProtoStream subclass: #Stream
  1653. instanceVariableNames: 'collection position streamSize'
  1654. package: 'Kernel-Collections'!
  1655. !Stream commentStamp!
  1656. I represent an accessor for a sequence of objects. This sequence is referred to as my "contents".
  1657. My instances are read/write streams to the contents sequence collection.!
  1658. !Stream methodsFor: 'accessing'!
  1659. collection
  1660. ^ collection
  1661. !
  1662. contents
  1663. ^ self collection
  1664. copyFrom: 1
  1665. to: self streamSize
  1666. !
  1667. position
  1668. ^ position ifNil: [ position := 0 ]
  1669. !
  1670. position: anInteger
  1671. position := anInteger
  1672. !
  1673. setCollection: aCollection
  1674. collection := aCollection
  1675. !
  1676. setStreamSize: anInteger
  1677. streamSize := anInteger
  1678. !
  1679. size
  1680. ^ self streamSize
  1681. !
  1682. streamSize
  1683. ^ streamSize
  1684. ! !
  1685. !Stream methodsFor: 'actions'!
  1686. close
  1687. !
  1688. flush
  1689. !
  1690. reset
  1691. self position: 0
  1692. !
  1693. resetContents
  1694. self reset.
  1695. self setStreamSize: 0
  1696. ! !
  1697. !Stream methodsFor: 'positioning'!
  1698. setToEnd
  1699. self position: self size
  1700. !
  1701. skip: anInteger
  1702. self position: ((self position + anInteger) min: self size max: 0)
  1703. ! !
  1704. !Stream methodsFor: 'reading'!
  1705. next
  1706. ^ self atEnd
  1707. ifTrue: [ nil ]
  1708. ifFalse: [
  1709. self position: self position + 1.
  1710. collection at: self position ]
  1711. !
  1712. next: anInteger
  1713. | tempCollection |
  1714. tempCollection := self collection class new.
  1715. anInteger timesRepeat: [
  1716. self atEnd ifFalse: [
  1717. tempCollection add: self next ]].
  1718. ^ tempCollection
  1719. !
  1720. peek
  1721. ^ self atEnd ifFalse: [
  1722. self collection at: self position + 1 ]
  1723. ! !
  1724. !Stream methodsFor: 'testing'!
  1725. atEnd
  1726. ^ self position = self size
  1727. !
  1728. atStart
  1729. ^ self position = 0
  1730. !
  1731. isEmpty
  1732. ^ self size = 0
  1733. ! !
  1734. !Stream methodsFor: 'writing'!
  1735. nextPut: anObject
  1736. self position: self position + 1.
  1737. self collection at: self position put: anObject.
  1738. self setStreamSize: (self streamSize max: self position)
  1739. ! !
  1740. !Stream class methodsFor: 'instance creation'!
  1741. on: aCollection
  1742. ^ self new
  1743. setCollection: aCollection;
  1744. setStreamSize: aCollection size;
  1745. yourself
  1746. ! !
  1747. Stream subclass: #StringStream
  1748. instanceVariableNames: ''
  1749. package: 'Kernel-Collections'!
  1750. !StringStream commentStamp!
  1751. I am a Stream specific to `String` objects.!
  1752. !StringStream methodsFor: 'reading'!
  1753. next: anInteger
  1754. | tempCollection |
  1755. tempCollection := self collection class new.
  1756. anInteger timesRepeat: [
  1757. self atEnd ifFalse: [
  1758. tempCollection := tempCollection, self next ]].
  1759. ^ tempCollection
  1760. ! !
  1761. !StringStream methodsFor: 'writing'!
  1762. cr
  1763. ^ self nextPutAll: String cr
  1764. !
  1765. crlf
  1766. ^ self nextPutAll: String crlf
  1767. !
  1768. lf
  1769. ^ self nextPutAll: String lf
  1770. !
  1771. nextPut: aString
  1772. self nextPutAll: aString
  1773. !
  1774. nextPutAll: aString
  1775. | pre post |
  1776. self atEnd ifTrue: [ self setCollection: self collection, aString ] ifFalse: [
  1777. pre := self collection copyFrom: 1 to: self position.
  1778. post := self collection copyFrom: (self position + 1 + aString size) to: self collection size.
  1779. self setCollection: pre, aString, post
  1780. ].
  1781. self position: self position + aString size.
  1782. self setStreamSize: (self streamSize max: self position)
  1783. !
  1784. nextPutString: aString
  1785. self nextPutAll: aString
  1786. !
  1787. space
  1788. self nextPut: ' '
  1789. !
  1790. tab
  1791. ^ self nextPutAll: String tab
  1792. ! !
  1793. Object subclass: #Queue
  1794. instanceVariableNames: 'read readIndex write'
  1795. package: 'Kernel-Collections'!
  1796. !Queue commentStamp!
  1797. I am a one-sided queue.
  1798. ## Usage
  1799. Use `#nextPut:` to add items to the queue.
  1800. Use `#next` or `#nextIfAbsent:` to get (and remove) the next item in the queue.
  1801. ## Implementation notes
  1802. A Queue uses two OrderedCollections inside,
  1803. `read` is at the front, is not modified and only read using `readIndex`.
  1804. `write` is at the back and is appended new items.
  1805. When `read` is exhausted, `write` is promoted to `read` and new `write` is created.
  1806. As a consequence, no data moving is done by me, write appending may do data moving
  1807. when growing `write`, but this is left to engine to implement as good as it chooses to.!
  1808. !Queue methodsFor: 'accessing'!
  1809. next
  1810. ^ self nextIfAbsent: [ self error: 'Cannot read from empty Queue.' ]
  1811. !
  1812. nextIfAbsent: aBlock
  1813. | result |
  1814. result := read at: readIndex ifAbsent: [
  1815. write isEmpty ifTrue: [
  1816. readIndex > 1 ifTrue: [ read := #(). readIndex := 1 ].
  1817. ^ aBlock value ].
  1818. read := write.
  1819. readIndex := 1.
  1820. write := OrderedCollection new.
  1821. read first ].
  1822. read at: readIndex put: nil.
  1823. readIndex := readIndex + 1.
  1824. ^ result
  1825. !
  1826. nextPut: anObject
  1827. write add: anObject
  1828. ! !
  1829. !Queue methodsFor: 'initialization'!
  1830. initialize
  1831. super initialize.
  1832. read := OrderedCollection new.
  1833. write := OrderedCollection new.
  1834. readIndex := 1
  1835. ! !
  1836. Object subclass: #RegularExpression
  1837. instanceVariableNames: ''
  1838. package: 'Kernel-Collections'!
  1839. !RegularExpression commentStamp!
  1840. I represent a regular expression object. My instances are JavaScript `RegExp` object.!
  1841. !RegularExpression methodsFor: 'evaluating'!
  1842. compile: aString
  1843. <return self.compile(aString)>
  1844. !
  1845. exec: aString
  1846. <return self.exec(aString) || nil>
  1847. !
  1848. test: aString
  1849. <return self.test(aString)>
  1850. ! !
  1851. !RegularExpression class methodsFor: 'instance creation'!
  1852. fromString: aString
  1853. ^ self fromString: aString flag: ''
  1854. !
  1855. fromString: aString flag: anotherString
  1856. <return new RegExp(aString, anotherString)>
  1857. ! !