Kernel-Collections.st 46 KB

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