Kernel-Collections.st 47 KB

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