Kernel-Collections.st 45 KB

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