2
0

Kernel-Collections.st 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  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. size
  1118. <return self.length>
  1119. ! !
  1120. !String methodsFor: 'comparing'!
  1121. < aString
  1122. <return String(self) < aString._asString()>
  1123. !
  1124. <= aString
  1125. <return String(self) <= aString._asString()>
  1126. !
  1127. = aString
  1128. ^ self == aString
  1129. !
  1130. == aString
  1131. <return aString !!= null && String(self) === (typeof aString === "string" ? aString : aString.valueOf())>
  1132. !
  1133. > aString
  1134. <return String(self) >> aString._asString()>
  1135. !
  1136. >= aString
  1137. <return String(self) >>= aString._asString()>
  1138. ! !
  1139. !String methodsFor: 'converting'!
  1140. asJSON
  1141. ^ self
  1142. !
  1143. asJavaScriptMethodName
  1144. <return $core.st2js(self)>
  1145. !
  1146. asJavascript
  1147. <
  1148. if(self.search(/^[a-zA-Z0-9_:.$ ]*$/) == -1)
  1149. return "\"" + self.replace(/[\x00-\x1f"\\\x7f-\x9f]/g, function(ch){var c=ch.charCodeAt(0);return "\\x"+("0"+c.toString(16)).slice(-2)}) + "\"";
  1150. else
  1151. return "\"" + self + "\"";
  1152. >
  1153. !
  1154. asLowercase
  1155. <return self.toLowerCase()>
  1156. !
  1157. asMutator
  1158. "Answer a setter selector. For example,
  1159. #name asMutator returns #name:"
  1160. self last = ':' ifFalse: [ ^ self, ':' ].
  1161. ^ self
  1162. !
  1163. asNumber
  1164. <return Number(self)>
  1165. !
  1166. asRegexp
  1167. ^ RegularExpression fromString: self
  1168. !
  1169. asString
  1170. ^ self
  1171. !
  1172. asSymbol
  1173. ^ self
  1174. !
  1175. asUppercase
  1176. <return self.toUpperCase()>
  1177. !
  1178. capitalized
  1179. ^ self isEmpty
  1180. ifTrue: [ self ]
  1181. ifFalse: [ self first asUppercase, self allButFirst ]
  1182. !
  1183. crlfSanitized
  1184. ^ self lines join: String lf
  1185. !
  1186. escaped
  1187. <return escape(self)>
  1188. !
  1189. reversed
  1190. <return self.split("").reverse().join("")>
  1191. !
  1192. unescaped
  1193. <return unescape(self)>
  1194. !
  1195. uriComponentDecoded
  1196. <return decodeURIComponent(self)>
  1197. !
  1198. uriComponentEncoded
  1199. <return encodeURIComponent(self)>
  1200. !
  1201. uriDecoded
  1202. <return decodeURI(self)>
  1203. !
  1204. uriEncoded
  1205. <return encodeURI(self)>
  1206. ! !
  1207. !String methodsFor: 'copying'!
  1208. , aString
  1209. <return String(self) + aString>
  1210. !
  1211. copyFrom: anIndex to: anotherIndex
  1212. <return self.substring(anIndex - 1, anotherIndex)>
  1213. !
  1214. deepCopy
  1215. ^ self shallowCopy
  1216. !
  1217. shallowCopy
  1218. ^ self class fromString: self
  1219. ! !
  1220. !String methodsFor: 'evaluating'!
  1221. value: anObject
  1222. ^ anObject perform: self
  1223. ! !
  1224. !String methodsFor: 'printing'!
  1225. printNl
  1226. <console.log(self)>
  1227. !
  1228. printOn: aStream
  1229. aStream
  1230. nextPutAll: '''';
  1231. nextPutAll: self;
  1232. nextPutAll: ''''
  1233. ! !
  1234. !String methodsFor: 'private'!
  1235. numericallyIndexable
  1236. <return String(self)>
  1237. ! !
  1238. !String methodsFor: 'regular expressions'!
  1239. match: aRegexp
  1240. <return self.search(aRegexp) !!= -1>
  1241. !
  1242. matchesOf: aRegularExpression
  1243. <return self.match(aRegularExpression)>
  1244. !
  1245. replace: aString with: anotherString
  1246. ^ self replaceRegexp: (RegularExpression fromString: aString flag: 'g') with: anotherString
  1247. !
  1248. replaceRegexp: aRegexp with: aString
  1249. <return self.replace(aRegexp, aString)>
  1250. !
  1251. trimBoth
  1252. ^ self trimBoth: '\s'
  1253. !
  1254. trimBoth: separators
  1255. ^ (self trimLeft: separators) trimRight: separators
  1256. !
  1257. trimLeft
  1258. ^ self trimLeft: '\s'
  1259. !
  1260. trimLeft: separators
  1261. ^ self replaceRegexp: (RegularExpression fromString: '^[', separators, ']+' flag: 'g') with: ''
  1262. !
  1263. trimRight
  1264. ^ self trimRight: '\s'
  1265. !
  1266. trimRight: separators
  1267. ^ self replaceRegexp: (RegularExpression fromString: '[', separators, ']+$' flag: 'g') with: ''
  1268. ! !
  1269. !String methodsFor: 'split join'!
  1270. join: aCollection
  1271. ^ String
  1272. streamContents: [ :stream | aCollection
  1273. do: [ :each | stream nextPutAll: each asString ]
  1274. separatedBy: [ stream nextPutAll: self ]]
  1275. !
  1276. lineIndicesDo: aBlock
  1277. "execute aBlock with 3 arguments for each line:
  1278. - start index of line
  1279. - end index of line without line delimiter
  1280. - end index of line including line delimiter(s) CR, LF or CRLF"
  1281. | cr lf start sz nextLF nextCR |
  1282. start := 1.
  1283. sz := self size.
  1284. cr := String cr.
  1285. nextCR := self indexOf: cr startingAt: 1.
  1286. lf := String lf.
  1287. nextLF := self indexOf: lf startingAt: 1.
  1288. [ start <= sz ] whileTrue: [
  1289. (nextLF = 0 and: [ nextCR = 0 ])
  1290. ifTrue: [ "No more CR, nor LF, the string is over"
  1291. aBlock value: start value: sz value: sz.
  1292. ^ self ].
  1293. (nextCR = 0 or: [ 0 < nextLF and: [ nextLF < nextCR ] ])
  1294. ifTrue: [ "Found a LF"
  1295. aBlock value: start value: nextLF - 1 value: nextLF.
  1296. start := 1 + nextLF.
  1297. nextLF := self indexOf: lf startingAt: start ]
  1298. ifFalse: [ 1 + nextCR = nextLF
  1299. ifTrue: [ "Found a CR-LF pair"
  1300. aBlock value: start value: nextCR - 1 value: nextLF.
  1301. start := 1 + nextLF.
  1302. nextCR := self indexOf: cr startingAt: start.
  1303. nextLF := self indexOf: lf startingAt: start ]
  1304. ifFalse: [ "Found a CR"
  1305. aBlock value: start value: nextCR - 1 value: nextCR.
  1306. start := 1 + nextCR.
  1307. nextCR := self indexOf: cr startingAt: start ] ]]
  1308. !
  1309. lineNumber: anIndex
  1310. "Answer a string containing the characters in the given line number."
  1311. | lineCount |
  1312. lineCount := 0.
  1313. self lineIndicesDo: [ :start :endWithoutDelimiters :end |
  1314. (lineCount := lineCount + 1) = anIndex ifTrue: [ ^ self copyFrom: start to: endWithoutDelimiters ]].
  1315. ^ nil
  1316. !
  1317. lines
  1318. "Answer an array of lines composing this receiver without the line ending delimiters."
  1319. | lines |
  1320. lines := Array new.
  1321. self linesDo: [ :aLine | lines add: aLine ].
  1322. ^ lines
  1323. !
  1324. linesDo: aBlock
  1325. "Execute aBlock with each line in this string. The terminating line
  1326. delimiters CR, LF or CRLF pairs are not included in what is passed to aBlock"
  1327. self lineIndicesDo: [ :start :endWithoutDelimiters :end |
  1328. aBlock value: (self copyFrom: start to: endWithoutDelimiters) ]
  1329. !
  1330. subStrings: aString
  1331. ^ self tokenize: aString
  1332. !
  1333. tokenize: aString
  1334. <return self.split(aString)>
  1335. ! !
  1336. !String methodsFor: 'testing'!
  1337. includesSubString: subString
  1338. <return self.indexOf(subString) !!= -1>
  1339. !
  1340. isCapitalized
  1341. ^ self first asUppercase == self first
  1342. !
  1343. isImmutable
  1344. ^ true
  1345. !
  1346. isString
  1347. ^ true
  1348. !
  1349. isVowel
  1350. "Answer true if the receiver is a one character string containing a voyel"
  1351. ^ self size = 1 and: [ 'aeiou' includes: self asLowercase ]
  1352. ! !
  1353. !String class methodsFor: 'accessing'!
  1354. cr
  1355. <return '\r'>
  1356. !
  1357. crlf
  1358. <return '\r\n'>
  1359. !
  1360. esc
  1361. ^ self fromCharCode: 27
  1362. !
  1363. lf
  1364. <return '\n'>
  1365. !
  1366. space
  1367. <return ' '>
  1368. !
  1369. streamClass
  1370. ^ StringStream
  1371. !
  1372. tab
  1373. <return '\t'>
  1374. ! !
  1375. !String class methodsFor: 'instance creation'!
  1376. fromCharCode: anInteger
  1377. <return String.fromCharCode(anInteger)>
  1378. !
  1379. fromString: aString
  1380. <return String(aString)>
  1381. !
  1382. value: aUTFCharCode
  1383. <return String.fromCharCode(aUTFCharCode);>
  1384. ! !
  1385. !String class methodsFor: 'random'!
  1386. random
  1387. "Returns random alphanumeric string beginning with letter"
  1388. <return (Math.random()*(22/32)+(10/32)).toString(32).slice(2);>
  1389. !
  1390. randomNotIn: aString
  1391. | result |
  1392. [ result := self random. aString includesSubString: result ] whileTrue.
  1393. ^ result
  1394. ! !
  1395. Collection subclass: #Set
  1396. instanceVariableNames: 'defaultBucket slowBucketStores fastBuckets size'
  1397. package: 'Kernel-Collections'!
  1398. !Set commentStamp!
  1399. I represent an unordered set of objects without duplicates.
  1400. ## Implementation notes
  1401. I put elements into different stores based on their type.
  1402. The goal is to store some elements into native JS object property names to be fast.
  1403. If an unboxed element has typeof 'string', 'boolean' or 'number', or an element is nil, null or undefined,
  1404. I store it as a property name in an empty (== Object.create(null)) JS object, different for each type
  1405. (for simplicity, nil/null/undefined is treated as one and included with the two booleans).
  1406. If element happen to be an object, I try to store them in `ArrayBucketStore`. I have two of them by default,
  1407. one hashed using the Smalltalk class name, the other one using the JS constructor name. It is possible to have more or less
  1408. instances of `ArrayBucketStores`, see `#initializeSlowBucketStores`.
  1409. As a last resort, if none of the `ArrayBucketStore` instances can find a suitable bucket, the `defaultBucket` is used,
  1410. which is an `Array`.!
  1411. !Set methodsFor: 'accessing'!
  1412. size
  1413. ^ size
  1414. ! !
  1415. !Set methodsFor: 'adding/removing'!
  1416. add: anObject
  1417. | bucket |
  1418. bucket := self bucketsOfElement: anObject.
  1419. ^ bucket second
  1420. ifNil: [
  1421. | object slowBucket |
  1422. object := bucket first.
  1423. slowBucket := bucket third.
  1424. slowBucket
  1425. indexOf: object
  1426. ifAbsent: [
  1427. slowBucket add: object.
  1428. size := size + 1 ].
  1429. object ]
  1430. ifNotNil: [ :primitiveBucket |
  1431. self
  1432. add: bucket first
  1433. in: primitiveBucket ]
  1434. !
  1435. remove: anObject ifAbsent: aBlock
  1436. | bucket |
  1437. bucket := self bucketsOfElement: anObject.
  1438. ^ bucket second
  1439. ifNil: [ bucket third remove: bucket first ifAbsent: [ ^aBlock value ]. size := size - 1 ]
  1440. ifNotNil: [ :primitiveBucket | self remove: bucket first in: primitiveBucket ]
  1441. !
  1442. removeAll
  1443. <
  1444. self['@fastBuckets'] = {
  1445. 'boolean': { store: Object.create(null), fn: function (x) { return {'true': true, 'false': false, 'null': null}[x]; } },
  1446. 'number': { store: Object.create(null), fn: Number },
  1447. 'string': { store: Object.create(null) }
  1448. };
  1449. self['@slowBucketStores'].forEach(function (x) { x._removeAll(); });
  1450. self['@defaultBucket']._removeAll();
  1451. self['@size'] = 0;
  1452. >
  1453. ! !
  1454. !Set methodsFor: 'comparing'!
  1455. = aCollection
  1456. self class = aCollection class ifFalse: [ ^ false ].
  1457. self size = aCollection size ifFalse: [ ^ false ].
  1458. self do: [ :each | (aCollection includes: each) ifFalse: [ ^ false ] ].
  1459. ^ true
  1460. ! !
  1461. !Set methodsFor: 'enumerating'!
  1462. collect: aBlock
  1463. | collection |
  1464. collection := self class new.
  1465. self do: [ :each | collection add: (aBlock value: each) ].
  1466. ^ collection
  1467. !
  1468. detect: aBlock ifNone: anotherBlock
  1469. self do: [ :each | (aBlock value: each) ifTrue: [ ^each ] ].
  1470. ^ anotherBlock value
  1471. !
  1472. do: aBlock
  1473. <
  1474. var el, keys, i;
  1475. el = self['@fastBuckets'];
  1476. keys = Object.keys(el);
  1477. for (i = 0; i < keys.length; ++i) {
  1478. var fastBucket = el[keys[i]], fn = fastBucket.fn, store = Object.keys(fastBucket.store);
  1479. if (fn) { for (var j = 0; j < store.length; ++j) { aBlock._value_(fn(store[j])); } }
  1480. else { store._do_(aBlock); }
  1481. }
  1482. el = self['@slowBucketStores'];
  1483. for (i = 0; i < el.length; ++i) { el[i]._do_(aBlock); }
  1484. self['@defaultBucket']._do_(aBlock);
  1485. >
  1486. !
  1487. select: aBlock
  1488. | collection |
  1489. collection := self class new.
  1490. self do: [ :each |
  1491. (aBlock value: each) ifTrue: [
  1492. collection add: each ] ].
  1493. ^ collection
  1494. ! !
  1495. !Set methodsFor: 'initialization'!
  1496. initialize
  1497. super initialize.
  1498. defaultBucket := #().
  1499. self
  1500. initializeSlowBucketStores;
  1501. removeAll
  1502. !
  1503. initializeSlowBucketStores
  1504. slowBucketStores := {
  1505. ArrayBucketStore hashBlock: [ :x | self classNameOf: x ].
  1506. ArrayBucketStore hashBlock: [ :x | self jsConstructorNameOf: x ]
  1507. }
  1508. ! !
  1509. !Set methodsFor: 'printing'!
  1510. printOn: aStream
  1511. super printOn: aStream.
  1512. aStream nextPutAll: ' ('.
  1513. self
  1514. do: [ :each | each printOn: aStream ]
  1515. separatedBy: [ aStream nextPutAll: ' ' ].
  1516. aStream nextPutAll: ')'
  1517. ! !
  1518. !Set methodsFor: 'private'!
  1519. add: anObject in: anotherObject
  1520. <
  1521. if (anObject in anotherObject.store) { return false; }
  1522. self['@size']++;
  1523. return anotherObject.store[anObject] = true;
  1524. >
  1525. !
  1526. bucketsOfElement: anObject
  1527. "Find the appropriate bucket for `anObject`.
  1528. For optimization purposes, directly answer an array with:
  1529. - the object to be store
  1530. - the primitive bucket
  1531. - the slow bucket"
  1532. <
  1533. var type, bucket, prim = anObject == null ? (anObject = nil) : anObject.valueOf();
  1534. if ((type = typeof prim) === "object") {
  1535. if (anObject !!== nil) {
  1536. bucket = null;
  1537. self['@slowBucketStores'].some(function (store) {
  1538. return bucket = store._bucketOfElement_(anObject);
  1539. });
  1540. return [ anObject, null, bucket || self['@defaultBucket'] ];
  1541. }
  1542. // include nil to well-known objects under 'boolean' fastBucket
  1543. prim = null;
  1544. type = 'boolean';
  1545. }
  1546. return [ prim, self['@fastBuckets'][type] ];
  1547. >
  1548. !
  1549. classNameOf: anObject
  1550. "Answer the class name of `anObject`, or `undefined`
  1551. if `anObject` is not an Smalltalk object"
  1552. <return anObject.klass !!= null && anObject.klass.className>
  1553. !
  1554. includes: anObject in: anotherObject
  1555. <return anObject in anotherObject.store>
  1556. !
  1557. jsConstructorNameOf: anObject
  1558. <return anObject.constructor && anObject.constructor.name>
  1559. !
  1560. remove: anObject in: anotherObject
  1561. <if (delete anotherObject.store[anObject]) self['@size']-->
  1562. ! !
  1563. !Set methodsFor: 'testing'!
  1564. includes: anObject
  1565. | bucket |
  1566. bucket := self bucketsOfElement: anObject.
  1567. ^ bucket second
  1568. ifNil: [ bucket third includes: bucket first ]
  1569. ifNotNil: [ :primitiveBucket | self includes: bucket first in: primitiveBucket ]
  1570. ! !
  1571. Object subclass: #ProtoStream
  1572. instanceVariableNames: ''
  1573. package: 'Kernel-Collections'!
  1574. !ProtoStream commentStamp!
  1575. I am the abstract base for different accessor for a sequence of objects. This sequence is referred to as my "contents".
  1576. My instances are read/write streams modifying the contents.!
  1577. !ProtoStream methodsFor: 'accessing'!
  1578. contents
  1579. self subclassResponsibility
  1580. ! !
  1581. !ProtoStream methodsFor: 'actions'!
  1582. reset
  1583. self subclassResponsibility
  1584. !
  1585. resetContents
  1586. self subclassResponsibility
  1587. ! !
  1588. !ProtoStream methodsFor: 'enumerating'!
  1589. do: aBlock
  1590. [ self atEnd ] whileFalse: [ aBlock value: self next ]
  1591. ! !
  1592. !ProtoStream methodsFor: 'positioning'!
  1593. setToEnd
  1594. self subclassResponsibility
  1595. !
  1596. setToStart
  1597. self reset
  1598. ! !
  1599. !ProtoStream methodsFor: 'reading'!
  1600. next
  1601. ^ self atEnd
  1602. ifTrue: [ nil ]
  1603. ifFalse: [ self subclassResponsibility ]
  1604. !
  1605. peek
  1606. ^ self atEnd
  1607. ifTrue: [ nil ]
  1608. ifFalse: [ self subclassResponsibility ]
  1609. ! !
  1610. !ProtoStream methodsFor: 'testing'!
  1611. atEnd
  1612. self subclassResponsibility
  1613. !
  1614. atStart
  1615. self subclassResponsibility
  1616. !
  1617. isEmpty
  1618. ^ self atStart and: [ self atEnd ]
  1619. ! !
  1620. !ProtoStream methodsFor: 'writing'!
  1621. << anObject
  1622. self write: anObject
  1623. !
  1624. nextPut: anObject
  1625. self subclassResponsibility
  1626. !
  1627. nextPutAll: aCollection
  1628. aCollection do: [ :each |
  1629. self nextPut: each ]
  1630. !
  1631. nextPutJSObject: aJSObject
  1632. self nextPut: aJSObject
  1633. !
  1634. nextPutString: aString
  1635. self nextPut: aString
  1636. !
  1637. write: anObject
  1638. anObject putOn: self
  1639. ! !
  1640. !ProtoStream class methodsFor: 'instance creation'!
  1641. on: aCollection
  1642. ^ self new
  1643. setCollection: aCollection;
  1644. setStreamSize: aCollection size;
  1645. yourself
  1646. ! !
  1647. ProtoStream subclass: #Stream
  1648. instanceVariableNames: 'collection position streamSize'
  1649. package: 'Kernel-Collections'!
  1650. !Stream commentStamp!
  1651. I represent an accessor for a sequence of objects. This sequence is referred to as my "contents".
  1652. My instances are read/write streams to the contents sequence collection.!
  1653. !Stream methodsFor: 'accessing'!
  1654. collection
  1655. ^ collection
  1656. !
  1657. contents
  1658. ^ self collection
  1659. copyFrom: 1
  1660. to: self streamSize
  1661. !
  1662. position
  1663. ^ position ifNil: [ position := 0 ]
  1664. !
  1665. position: anInteger
  1666. position := anInteger
  1667. !
  1668. setCollection: aCollection
  1669. collection := aCollection
  1670. !
  1671. setStreamSize: anInteger
  1672. streamSize := anInteger
  1673. !
  1674. size
  1675. ^ self streamSize
  1676. !
  1677. streamSize
  1678. ^ streamSize
  1679. ! !
  1680. !Stream methodsFor: 'actions'!
  1681. close
  1682. !
  1683. flush
  1684. !
  1685. reset
  1686. self position: 0
  1687. !
  1688. resetContents
  1689. self reset.
  1690. self setStreamSize: 0
  1691. ! !
  1692. !Stream methodsFor: 'positioning'!
  1693. setToEnd
  1694. self position: self size
  1695. !
  1696. skip: anInteger
  1697. self position: ((self position + anInteger) min: self size max: 0)
  1698. ! !
  1699. !Stream methodsFor: 'reading'!
  1700. next
  1701. ^ self atEnd
  1702. ifTrue: [ nil ]
  1703. ifFalse: [
  1704. self position: self position + 1.
  1705. collection at: self position ]
  1706. !
  1707. next: anInteger
  1708. | tempCollection |
  1709. tempCollection := self collection class new.
  1710. anInteger timesRepeat: [
  1711. self atEnd ifFalse: [
  1712. tempCollection add: self next ]].
  1713. ^ tempCollection
  1714. !
  1715. peek
  1716. ^ self atEnd ifFalse: [
  1717. self collection at: self position + 1 ]
  1718. ! !
  1719. !Stream methodsFor: 'testing'!
  1720. atEnd
  1721. ^ self position = self size
  1722. !
  1723. atStart
  1724. ^ self position = 0
  1725. !
  1726. isEmpty
  1727. ^ self size = 0
  1728. ! !
  1729. !Stream methodsFor: 'writing'!
  1730. nextPut: anObject
  1731. self position: self position + 1.
  1732. self collection at: self position put: anObject.
  1733. self setStreamSize: (self streamSize max: self position)
  1734. ! !
  1735. !Stream class methodsFor: 'instance creation'!
  1736. on: aCollection
  1737. ^ self new
  1738. setCollection: aCollection;
  1739. setStreamSize: aCollection size;
  1740. yourself
  1741. ! !
  1742. Stream subclass: #StringStream
  1743. instanceVariableNames: ''
  1744. package: 'Kernel-Collections'!
  1745. !StringStream commentStamp!
  1746. I am a Stream specific to `String` objects.!
  1747. !StringStream methodsFor: 'reading'!
  1748. next: anInteger
  1749. | tempCollection |
  1750. tempCollection := self collection class new.
  1751. anInteger timesRepeat: [
  1752. self atEnd ifFalse: [
  1753. tempCollection := tempCollection, self next ]].
  1754. ^ tempCollection
  1755. ! !
  1756. !StringStream methodsFor: 'writing'!
  1757. cr
  1758. ^ self nextPutAll: String cr
  1759. !
  1760. crlf
  1761. ^ self nextPutAll: String crlf
  1762. !
  1763. lf
  1764. ^ self nextPutAll: String lf
  1765. !
  1766. nextPut: aString
  1767. self nextPutAll: aString
  1768. !
  1769. nextPutAll: aString
  1770. | pre post |
  1771. self atEnd ifTrue: [ self setCollection: self collection, aString ] ifFalse: [
  1772. pre := self collection copyFrom: 1 to: self position.
  1773. post := self collection copyFrom: (self position + 1 + aString size) to: self collection size.
  1774. self setCollection: pre, aString, post
  1775. ].
  1776. self position: self position + aString size.
  1777. self setStreamSize: (self streamSize max: self position)
  1778. !
  1779. nextPutString: aString
  1780. self nextPutAll: aString
  1781. !
  1782. space
  1783. self nextPut: ' '
  1784. !
  1785. tab
  1786. ^ self nextPutAll: String tab
  1787. ! !
  1788. Object subclass: #Queue
  1789. instanceVariableNames: 'read readIndex write'
  1790. package: 'Kernel-Collections'!
  1791. !Queue commentStamp!
  1792. I am a one-sided queue.
  1793. ## Usage
  1794. Use `#nextPut:` to add items to the queue.
  1795. Use `#next` or `#nextIfAbsent:` to get (and remove) the next item in the queue.
  1796. ## Implementation notes
  1797. A Queue uses two OrderedCollections inside,
  1798. `read` is at the front, is not modified and only read using `readIndex`.
  1799. `write` is at the back and is appended new items.
  1800. When `read` is exhausted, `write` is promoted to `read` and new `write` is created.
  1801. As a consequence, no data moving is done by me, write appending may do data moving
  1802. when growing `write`, but this is left to engine to implement as good as it chooses to.!
  1803. !Queue methodsFor: 'accessing'!
  1804. next
  1805. ^ self nextIfAbsent: [ self error: 'Cannot read from empty Queue.' ]
  1806. !
  1807. nextIfAbsent: aBlock
  1808. | result |
  1809. result := read at: readIndex ifAbsent: [
  1810. write isEmpty ifTrue: [
  1811. readIndex > 1 ifTrue: [ read := #(). readIndex := 1 ].
  1812. ^ aBlock value ].
  1813. read := write.
  1814. readIndex := 1.
  1815. write := OrderedCollection new.
  1816. read first ].
  1817. read at: readIndex put: nil.
  1818. readIndex := readIndex + 1.
  1819. ^ result
  1820. !
  1821. nextPut: anObject
  1822. write add: anObject
  1823. ! !
  1824. !Queue methodsFor: 'initialization'!
  1825. initialize
  1826. super initialize.
  1827. read := OrderedCollection new.
  1828. write := OrderedCollection new.
  1829. readIndex := 1
  1830. ! !
  1831. Object subclass: #RegularExpression
  1832. instanceVariableNames: ''
  1833. package: 'Kernel-Collections'!
  1834. !RegularExpression commentStamp!
  1835. I represent a regular expression object. My instances are JavaScript `RegExp` object.!
  1836. !RegularExpression methodsFor: 'evaluating'!
  1837. compile: aString
  1838. <return self.compile(aString)>
  1839. !
  1840. exec: aString
  1841. <return self.exec(aString) || nil>
  1842. !
  1843. test: aString
  1844. <return self.test(aString)>
  1845. ! !
  1846. !RegularExpression class methodsFor: 'instance creation'!
  1847. fromString: aString
  1848. ^ self fromString: aString flag: ''
  1849. !
  1850. fromString: aString flag: anotherString
  1851. <return new RegExp(aString, anotherString)>
  1852. ! !