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