Fast String Truncated Width
A fast function for calculating where a string should be truncated, given a width limit and an ellipsis string.
This is a low-level function that basically calculates the visual width of a string and the index at which it should be truncated once printed to the terminal, but taking into account an optional width limit and an optional ellipsis string, so that the string doesn't have to be processed multiple times to be truncated, and how long the part after the truncation point is doesn't cost us anything because we can just ignore it.
Note that codepoints considered "ambiguous" in Unicode will always use "regularWidth" as their width, if you need to customize this you should use string-width instead.
Install
npm install fast-string-truncated-width
Usage
import fastStringTruncatedWidth from 'fast-string-truncated-width';
const widthOptions = {
controlWidth: 0,
tabWidth: 8,
emojiWidth: 2,
regularWidth: 1,
wideWidth: 2
};
const result1 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: Infinity, ellipsis: '…' }, widthOptions );
result1.truncated;
result1.ellipsed;
result1.width;
result1.index;
const result2 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: 3, ellipsis: '…' }, widthOptions );
result2.truncated;
result2.ellipsed;
result2.width;
result2.index;
const input = '\x1b[31mhello';
const options = { limit: 3, ellipsis: '…' };
const result3 = fastStringTruncatedWidth ( input, options, widthOptions );
const output = `${input.slice ( 0, result3.index )}${result3.ellipsed ? options.ellipsis : ''}`;
License
MIT © Fabio Spampinato