Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Nodonisko/fec494bf536423c102024d0ba78fa9b1 to your computer and use it in GitHub Desktop.

Select an option

Save Nodonisko/fec494bf536423c102024d0ba78fa9b1 to your computer and use it in GitHub Desktop.
utf8ToBytes.js
function utf8ToBytes(string, unitsInput) {
let units;
// Mimic the polyfill's `units = units || Infinity` behavior for common falsy values
// that would lead to `Infinity` in the original.
if (unitsInput === undefined ||
unitsInput === null ||
unitsInput === 0 || // Original `|| Infinity` makes 0 effectively Infinity
(typeof unitsInput === 'number' && Number.isNaN(unitsInput))) {
units = Infinity;
} else {
units = Number(unitsInput); // Coerce to number (e.g., if it was a string "10")
if (Number.isNaN(units)) { // If coercion results in NaN (e.g., from "abc")
units = Infinity;
}
}
const encoder = new TextEncoder(); // UTF-8 by default
const uint8Array = encoder.encode(string);
let finalUint8Array;
if (units < 0) {
// If units was specified as a negative number not caught by the Infinity conditions.
// The polyfill would also likely break immediately or produce no bytes.
finalUint8Array = new Uint8Array(0);
} else if (units !== Infinity && uint8Array.length > units) {
// Truncate if the encoded length is greater than the specified units.
// Ensure units is not negative for slice, though above logic should handle most.
finalUint8Array = uint8Array.slice(0, Math.max(0, units));
} else {
// No truncation needed or units is Infinity
finalUint8Array = uint8Array;
}
return finalUint8Array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment