1
0

Kernel-Collections.st 44 KB

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