UNPKG

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