1
0

Kernel-Collections.st 45 KB

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