Skip to content

Commit 8d80187

Browse files
committed
feat(util): 🎸 add another Uint8Array comparison function
1 parent 04ec019 commit 8d80187

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/util/buffers/cmpUint8Array2.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
/**
2+
* Compares two `Uint8Arrays` byte-by-byte. Returns a negative number if `a` is
3+
* less than `b`, a positive number if `a` is greater than `b`, or 0 if `a` is
4+
* equal to `b`.
5+
*
6+
* @returns A negative number if a is less than b, a positive number if a is
7+
* greater than b, or 0 if a is equal to b.
8+
*/
19
export const cmpUint8Array2 = (a: Uint8Array, b: Uint8Array): number => {
210
const len1 = a.length;
311
const len2 = b.length;

src/util/buffers/cmpUint8Array3.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Compares two `Uint8Arrays`, first by length, then by each byte. Returns a
3+
* negative number if `a` is less than `b`, a positive number if `a` is greater
4+
* than `b`, or 0 if `a` is equal to `b`.
5+
*
6+
* @returns A negative number if a is less than b, a positive number if a is
7+
* greater than b, or 0 if a is equal to b.
8+
*/
9+
export const cmpUint8Array3 = (a: Uint8Array, b: Uint8Array): number => {
10+
const len1 = a.length;
11+
const len2 = b.length;
12+
const diff = len1 - len2;
13+
if (diff !== 0) return diff;
14+
for (let i = 0; i < len1; i++) {
15+
const diff = a[i] - b[i];
16+
if (diff !== 0) return diff;
17+
}
18+
return 0;
19+
};

0 commit comments

Comments
 (0)