Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ascii encoding conversion #10

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,16 @@ console.log(hexToUint8Array('48656c6c6f'));
```
*/
export function hexToUint8Array(hexString: string): Uint8Array;

/**
Convert a string to a `Uint8Array` using ASCII encoding.

@example
```
import { asciiStringToUint8Array } from 'uint8array-extras';

console.log(asciiStringToUint8Array('Hello'));
//=> Uint8Array [72, 101, 108, 108, 111]
```
*/
export function asciiStringToUint8Array(string: string): Uint8Array;
16 changes: 16 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,19 @@

return bytes;
}

export function asciiStringToUint8Array(string) {
assertString(string);

const bytes = new Uint8Array(string.length);

for (let i = 0; i < string.length; i++) {
const code = string.charCodeAt(i);

Check failure on line 230 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 20

Prefer `String#codePointAt()` over `String#charCodeAt()`.

Check failure on line 230 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 18

Prefer `String#codePointAt()` over `String#charCodeAt()`.

Check failure on line 230 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 20

Prefer `String#codePointAt()` over `String#charCodeAt()`.

Check failure on line 230 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 18

Prefer `String#codePointAt()` over `String#charCodeAt()`.
if (code > 127) {
throw new Error(`Non-ASCII character detected at position ${i}`);
}
bytes[i] = code;

Check failure on line 234 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 20

Expected blank line before this statement.

Check failure on line 234 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 18

Expected blank line before this statement.

Check failure on line 234 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 20

Expected blank line before this statement.

Check failure on line 234 in index.js

View workflow job for this annotation

GitHub Actions / Node.js 18

Expected blank line before this statement.
}

return bytes;
}
Loading