Skip to content

Instantly share code, notes, and snippets.

@taosx
Created June 1, 2023 07:52
Show Gist options
  • Save taosx/2a18cafa049c0b1f21a49bf1db0b7b2a to your computer and use it in GitHub Desktop.
Save taosx/2a18cafa049c0b1f21a49bf1db0b7b2a to your computer and use it in GitHub Desktop.
strcmp for uint8array in javascript/typescript
// not tested (just a test)
// fastest I've tested on chrome
function strcmpBitWise(a: Uint8Array, b: Uint8Array): number {
var diff;
for (let i = 0; i < Math.min(a.length, b.length); i++) {
diff = a[i] ^ b[i];
if (diff !== 0) return diff;
}
return a.length - b.length;
}
// work a bit faster on bun/safari (something about Math.min)
function strcmpBitWise(a: Uint8Array, b: Uint8Array): number {
var diff;
for (let i = 0; i < (a.length < b.length ? a.length : b.length); i++) {
diff = a[i] ^ b[i];
if (diff !== 0) return diff;
}
return a.length - b.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment