@@ -141,13 +141,7 @@ export function baseX <Base extends string, Prefix extends string> ({ name, pref
141
141
} )
142
142
}
143
143
144
- function decode ( string : string , alphabet : string , bitsPerChar : number , name : string ) : Uint8Array {
145
- // Build the character lookup table:
146
- const codes : Record < string , number > = { }
147
- for ( let i = 0 ; i < alphabet . length ; ++ i ) {
148
- codes [ alphabet [ i ] ] = i
149
- }
150
-
144
+ function decode ( string : string , alphabetIdx : Record < string , number > , bitsPerChar : number , name : string ) : Uint8Array {
151
145
// Count the padding bytes:
152
146
let end = string . length
153
147
while ( string [ end - 1 ] === '=' ) {
@@ -163,7 +157,7 @@ function decode (string: string, alphabet: string, bitsPerChar: number, name: st
163
157
let written = 0 // Next byte to write
164
158
for ( let i = 0 ; i < end ; ++ i ) {
165
159
// Read one character from the string:
166
- const value = codes [ string [ i ] ]
160
+ const value = alphabetIdx [ string [ i ] ]
167
161
if ( value === undefined ) {
168
162
throw new SyntaxError ( `Non-${ name } character` )
169
163
}
@@ -221,18 +215,28 @@ function encode (data: Uint8Array, alphabet: string, bitsPerChar: number): strin
221
215
return out
222
216
}
223
217
218
+ function createAlphabetIdx ( alphabet : string ) : Record < string , number > {
219
+ // Build the character lookup table:
220
+ const alphabetIdx : Record < string , number > = { }
221
+ for ( let i = 0 ; i < alphabet . length ; ++ i ) {
222
+ alphabetIdx [ alphabet [ i ] ] = i
223
+ }
224
+ return alphabetIdx
225
+ }
226
+
224
227
/**
225
228
* RFC4648 Factory
226
229
*/
227
230
export function rfc4648 < Base extends string , Prefix extends string > ( { name, prefix, bitsPerChar, alphabet } : { name : Base , prefix : Prefix , bitsPerChar : number , alphabet : string } ) : Codec < Base , Prefix > {
231
+ const alphabetIdx = createAlphabetIdx ( alphabet )
228
232
return from ( {
229
233
prefix,
230
234
name,
231
235
encode ( input : Uint8Array ) : string {
232
236
return encode ( input , alphabet , bitsPerChar )
233
237
} ,
234
238
decode ( input : string ) : Uint8Array {
235
- return decode ( input , alphabet , bitsPerChar , name )
239
+ return decode ( input , alphabetIdx , bitsPerChar , name )
236
240
}
237
241
} )
238
242
}
0 commit comments