| encode decode |
encode := [:text | | dictionary next phrase joined output |
 dictionary := Dictionary new.
 dictionary at: 'A' put: 1; at: 'B' put: 2.
 next := 3. phrase := ''. output := OrderedCollection new.
 text do: [:character |
  ('AB' includes: character) ifFalse: [Error signal: 'Use only A and B'].
  joined := phrase, character asString.
  (dictionary includesKey: joined)
   ifTrue: [phrase := joined]
   ifFalse: [
    output add: (dictionary at: phrase).
    next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
    dictionary at: joined put: next. next := next + 1.
    phrase := character asString]].
 phrase isEmpty ifFalse: [output add: (dictionary at: phrase)].
 output asArray].
decode := [:codes | | dictionary next previous entry output |
 dictionary := Dictionary new.
 dictionary at: 1 put: 'A'; at: 2 put: 'B'.
 next := 3. previous := nil. output := WriteStream on: String new.
 codes do: [:number |
  (number isInteger and: [number > 0])
   ifFalse: [Error signal: 'Use positive integer codes'].
  entry := dictionary at: number ifAbsent: [
   (previous notNil and: [number = next])
    ifTrue: [previous, previous first asString]
    ifFalse: [Error signal: 'Unknown code']].
  output nextPutAll: entry.
  previous notNil ifTrue: [
   next > 256 ifTrue: [Error signal: 'Dictionary capacity reached'].
   dictionary at: next put: previous, entry first asString.
   next := next + 1].
  previous := entry].
 output contents].
{decode value: #(1 2 3 5).
 #('' 'A' 'B' 'AAA' 'ABABABA' 'BAABAAB')
  collect: [:text | (decode value: (encode value: text)) = text]}
