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.
Install
npm install --save fast-string-truncated-width
Usage
import fastStringTruncatedWidth from 'fast-string-truncated-width';
const result1 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: Infinity, ellipsis: '…' } );
result1.truncated;
result1.ellipsed;
result1.width;
result1.index;
const result2 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: 3, ellipsis: '…' } );
result2.truncated;
result2.ellipsed;
result2.width;
result2.index;
const input = '\x1b[31mhello';
const options = { limit: 3, ellipsis: '…' };
const result3 = fastStringTruncatedWidth ( input, options );
const output = `${input.slice ( 0, result3.index )}${result3.ellipsed ? options.ellipsis : ''}`;
License
MIT © Fabio Spampinato