UNPKG

1.33 kBJavaScriptView Raw
1import { u8aToU8a } from './toU8a.js';
2/**
3 * @name u8aCmp
4 * @summary Compares two Uint8Arrays for sorting.
5 * @description
6 * For `UInt8Array` (or hex string) input values returning -1, 0 or +1
7 * @example
8 * <BR>
9 *
10 * ```javascript
11 * import { u8aCmp } from '@polkadot/util';
12 *
13 * u8aCmp(new Uint8Array([0x67, 0x65]), new Uint8Array([0x68, 0x65])); // -1
14 * u8aCmp(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // 0
15 * u8aCmp(new Uint8Array([0x69, 0x65]), new Uint8Array([0x68, 0x65])); // +1
16 * ```
17 */
18export function u8aCmp(a, b) {
19 const u8aa = u8aToU8a(a);
20 const u8ab = u8aToU8a(b);
21 let i = 0;
22 while (true) {
23 const overA = i >= u8aa.length;
24 const overB = i >= u8ab.length;
25 if (overA && overB) {
26 // both ends reached
27 return 0;
28 }
29 else if (overA) {
30 // a has no more data, b has data
31 return -1;
32 }
33 else if (overB) {
34 // b has no more data, a has data
35 return 1;
36 }
37 else if (u8aa[i] !== u8ab[i]) {
38 // the number in this index doesn't match
39 // (we don't use u8aa[i] - u8ab[i] since that doesn't match with localeCompare)
40 return u8aa[i] > u8ab[i]
41 ? 1
42 : -1;
43 }
44 i++;
45 }
46}