Kernel-Collections.st 51 KB

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