Skip to content

Commit

Permalink
Add CharacterCollection>>#format:
Browse files Browse the repository at this point in the history
  • Loading branch information
gcotelli committed Jun 18, 2024
1 parent 4fea7c4 commit 3cbf2ff
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,31 @@ CharacterCollection >> findTokens: delimiters [
^ self substrings: separators
]

{ #category : '*Buoy-Collections-GS64-Extensions' }
CharacterCollection >> format: collection [
"Format the receiver by interpolating elements from collection"

^ self species new: self size streamContents: [ :result |
| stream |
stream := self readStream.
[ stream atEnd ] whileFalse: [
| currentChar |
( currentChar := stream next ) == ${
ifTrue: [
| expression index |
expression := stream upTo: $}.
index := Integer readFrom: expression ifFail: [ expression ].
result nextPutAll: ( collection at: index ) asString
]
ifFalse: [
currentChar == $\
ifTrue: [ stream atEnd ifFalse: [ result nextPut: stream next ] ]
ifFalse: [ result nextPut: currentChar ]
]
]
]
]

{ #category : '*Buoy-Collections-GS64-Extensions' }
CharacterCollection >> includesSubstring: substring [

Expand Down
28 changes: 28 additions & 0 deletions source/Buoy-Collections-Tests/StringExtensionsTest.class.st
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,34 @@ StringExtensionsTest >> testFindTokens [
hasTheSameElementsInTheSameOrderThat: #( 'es' ' ' 'his' )
]

{ #category : 'tests' }
StringExtensionsTest >> testFormat [

self
assert: ( 'This is {1} !' format: #( 'a test' ) ) equals: 'This is a test !';
assert: ( 'This is a {type}' format: { ( 'type' -> 'test' ) } asDictionary )
equals: 'This is a test';
assert: ( 'In {1} you can escape \{ by prefixing it with \\' format: { 'strings' } )
equals: 'In strings you can escape { by prefixing it with \';
assert: ( 'In \{1\} you can escape \{ by prefixing it with \\' format: { 'strings' } )
equals: 'In {1} you can escape { by prefixing it with \';
assert: ( '\{ \} \\ foo {1} bar {2}' format: { 12 . 'string' } )
equals: '{ } \ foo 12 bar string';
assert: ( '\{1}' format: { } ) equals: '{1}';
assert: ( '\{1}{1}' format: { $a } ) equals: '{1}a';
assert: ( '{1}{1}' format: { $a } ) equals: 'aa'
]

{ #category : 'tests' }
StringExtensionsTest >> testFormatWhenInvalid [

self
should: [ 'Invalid {1}' format: #( ) ] raise: SubscriptOutOfBounds;
should: [ 'Invalid {date}' format: #( 1 2 ) ] raise: Error;
should: [ '{ 1 }' format: #( 1 ) ] raise: Error;
should: [ '{ date }' format: { 'date' -> 1 } asDictionary ] raise: NotFound
]

{ #category : 'tests' }
StringExtensionsTest >> testIncludesSubstring [

Expand Down

0 comments on commit 3cbf2ff

Please sign in to comment.