cjke-strings
Version:
a set of Chinese Japanese Korean and Emoji strings helpers
52 lines • 1.7 kB
JavaScript
import { everything } from './base.js';
import { readFirstCompleteChar } from './firstCompleteChar.js';
function returnValue(original, length, width) {
const result = Number.isFinite(length) ? original.slice(0, length) : original;
const remaining = Number.isFinite(length) ? original.slice(length) : '';
return {
result,
width,
remaining,
toString() {
return result;
},
[Symbol.toPrimitive]() {
return result;
},
};
}
export function limitWidth(original, limit, supports = everything) {
let width = 0;
let str = original;
while (str.length > 0) {
const item = readFirstCompleteChar(str, supports);
const nextWidth = width + item.width;
if (nextWidth > limit) {
return returnValue(original, original.length - str.length, width);
}
width += item.width;
if (width === limit) {
return returnValue(original, original.length - str.length + item.length, width);
}
str = str.slice(item.length);
}
return returnValue(original, Number.POSITIVE_INFINITY, width);
}
export function chunkText(text, width, supports = everything) {
const result = [];
while (text.length > 0) {
const item = limitWidth(text, width, supports);
result.push(item.toString());
text = item.remaining;
}
return result;
}
export function boxText(text, width, supports = everything) {
const lines = text.split('\n');
const result = [];
for (const line of lines) {
result.push(...chunkText(line, width, supports));
}
return result;
}
//# sourceMappingURL=limitWidth.js.map