Kernel-Collections.st 45 KB

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