Created
June 2, 2025 18:16
-
-
Save Nodonisko/fec494bf536423c102024d0ba78fa9b1 to your computer and use it in GitHub Desktop.
utf8ToBytes.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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