scroll/src/common/utils.ts

91 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-11-16 16:00:03 -05:00
// ----------------------------------------------------------------------------
// Misc
// ----------------------------------------------------------------------------
export const noop = () => {};
2023-11-16 13:00:02 -05:00
2023-11-10 08:36:18 -05:00
// ----------------------------------------------------------------------------
2023-11-09 12:32:41 -05:00
// Strings
2023-11-10 08:36:18 -05:00
// ----------------------------------------------------------------------------
2023-11-09 12:32:41 -05:00
2023-11-16 16:00:03 -05:00
/**
* Get the codepoint of the first byte of a string. If the string
* is empty, this will return 256
*
* @param s - the string
*/
export function ord(s: string): number {
if (s.length > 0) {
return s.codePointAt(0)!;
}
return 256;
}
2023-11-02 13:06:48 -04:00
/**
* Split a string by graphemes, not just bytes
2023-11-16 16:00:03 -05:00
*
2023-11-02 13:06:48 -04:00
* @param s - the string to split into 'characters'
*/
export function chars(s: string): string[] {
return s.split(/(?:)/u);
}
2023-11-09 12:05:30 -05:00
/**
* Get the 'character length' of a string, not its UTF16 byte count
2023-11-16 16:00:03 -05:00
*
2023-11-09 12:05:30 -05:00
* @param s - the string to check
*/
export function strlen(s: string): number {
return chars(s).length;
}
2023-11-02 13:06:48 -04:00
/**
2023-11-16 16:00:03 -05:00
* Are all the characters in the string in ASCII range?
2023-11-02 13:06:48 -04:00
*
2023-11-16 16:00:03 -05:00
* @param char - string to check
2023-11-02 13:06:48 -04:00
*/
export function is_ascii(char: string): boolean {
2023-11-16 16:00:03 -05:00
return chars(char).every((char) => ord(char) < 0x80);
2023-11-02 13:06:48 -04:00
}
/**
* Is the one char in the string an ascii control character?
*
* @param char - a one character string to check
*/
export function is_control(char: string): boolean {
2023-11-16 16:00:03 -05:00
const code = ord(char);
2023-11-02 13:06:48 -04:00
return is_ascii(char) && (code === 0x7f || code < 0x20);
}
/**
* Get the key code for a ctrl chord
2023-11-16 16:00:03 -05:00
*
2023-11-02 13:06:48 -04:00
* @param char - a one character string
*/
export function ctrl_key(char: string): string {
// This is the normal use case, of course
if (is_ascii(char)) {
2023-11-16 16:00:03 -05:00
const point = ord(char);
2023-11-02 13:06:48 -04:00
return String.fromCodePoint(point & 0x1f);
}
// If it's not ascii, just return the input key code
return char;
}
2023-11-09 12:05:30 -05:00
/**
* Trim a string to a max number of characters
* @param s
* @param maxLen
*/
export function truncate(s: string, maxLen: number): string {
const chin = chars(s);
if (maxLen >= chin.length) {
return s;
}
return chin.slice(0, maxLen).join('');
}