Skip to content

Commit fc59f5b

Browse files
committed
refactor: improve multiaddrHexToHuman and taskResultToObject for better readability and performance
1 parent 2d98279 commit fc59f5b

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/utils/format.ts

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,37 @@
11
import { multiaddr } from '@multiformats/multiaddr';
22

33
export const multiaddrHexToHuman = (hexString: string): string => {
4-
if (hexString.substring(0, 2) !== '0x') return hexString;
5-
let res: string;
6-
const buffer: Buffer = Buffer.from(hexString.substring(2), 'hex');
4+
if (!hexString.startsWith('0x')) return hexString;
5+
6+
const buffer = Uint8Array.from(
7+
hexString
8+
.substring(2)
9+
.match(/.{1,2}/g)!
10+
.map((byte) => parseInt(byte, 16))
11+
);
12+
713
try {
8-
res = multiaddr(new Uint8Array(buffer)).toString();
14+
return multiaddr(buffer).toString();
915
} catch {
10-
res = buffer.toString();
16+
return new TextDecoder().decode(buffer);
1117
}
12-
return res;
1318
};
1419

1520
export const taskResultToObject = (results?: string | null) => {
1621
let resultObj = { storage: 'none' };
22+
1723
try {
1824
if (results && results !== '0x') {
19-
resultObj = JSON.parse(
20-
Buffer.from(results.substring(2), 'hex').toString('utf8')
25+
const hex = results.slice(2);
26+
const bytes = Uint8Array.from(
27+
hex.match(/.{1,2}/g)!.map((b) => parseInt(b, 16))
2128
);
29+
const json = new TextDecoder().decode(bytes);
30+
resultObj = JSON.parse(json);
2231
}
2332
} catch {
2433
// nothing to do
2534
}
35+
2636
return resultObj;
2737
};

0 commit comments

Comments
 (0)