@@ -132,17 +132,29 @@ export function calculateAddressRange(
132
132
* [1, 2, a, b] -> Nibbles(is_odd_length=false, packed_nibbles=[0x12, 0xab])
133
133
* [1, 2, a, b, c] -> Nibbles(is_odd_length=true, packed_nibbles=[0x01, 0x2a, 0xbc])
134
134
*/
135
- export const tightlyPackNibbles = ( nibbles : TNibble [ ] ) : TNibbles => {
136
- if ( ! nibbles . every ( ( nibble ) => Nibble [ nibble ] !== undefined ) ) {
137
- throw new Error ( `path: [${ nibbles } ] must be an array of nibbles` )
135
+ export const tightlyPackNibbles = ( _nibbles : TNibble [ ] ) : TNibbles => {
136
+ if ( ! _nibbles . every ( ( nibble ) => Nibble [ nibble ] !== undefined ) ) {
137
+ throw new Error ( `path: [${ _nibbles } ] must be an array of nibbles` )
138
138
}
139
+ const nibbles : number [ ] = _nibbles . map ( ( nibble ) =>
140
+ typeof nibble === 'string' ? parseInt ( nibble , 16 ) : nibble ,
141
+ )
139
142
const isOddLength = nibbles . length % 2 !== 0
140
- const nibbleArray = isOddLength ? [ '0' , ...nibbles ] : nibbles
143
+ const nibbleArray = isOddLength ? [ 0 , ...nibbles ] : nibbles
141
144
const nibblePairs = Array . from ( { length : nibbleArray . length / 2 } , ( _ , idx ) => idx ) . map ( ( i ) => {
142
145
return nibbleArray . slice ( 2 * i , 2 * i + 2 ) as [ TNibble , TNibble ]
143
146
} )
144
- const packedBytes = nibblePairs . map ( ( nibbles ) => {
145
- return parseInt ( nibbles . join ( '' ) , 16 )
147
+ const packedBytes = nibblePairs . map ( ( [ a , b ] ) => {
148
+ return parseInt ( a . toString ( 16 ) + b . toString ( 16 ) , 16 )
146
149
} )
147
150
return { isOddLength, packedNibbles : Uint8Array . from ( packedBytes ) }
148
151
}
152
+
153
+ export const unpackNibbles = ( packedNibbles : Uint8Array , isOddLength : boolean ) : TNibble [ ] => {
154
+ const unpacked = packedNibbles . reduce ( ( acc , byte , _idx , _array ) => {
155
+ acc . push ( ( byte >>> 4 ) as TNibble )
156
+ acc . push ( ( byte & 0x0f ) as TNibble )
157
+ return acc
158
+ } , [ ] as TNibble [ ] )
159
+ return isOddLength ? unpacked . slice ( 1 ) : unpacked
160
+ }
0 commit comments