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';// The width of various classes of characters is configurableconst widthOptions = { controlWidth: 0, tabWidth: 8, emojiWidth: 2, regularWidth: 1, wideWidth: 2};// Retrieving the result for a string that fits within our width limitconst result1 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: Infinity, ellipsis: '…' }, widthOptions );result1.truncated; // => false, the string fits within the width limit, it doesn't have to be truncatedresult1.ellipsed; // => false, the ellipsis string doesn't need to be appended to the stringresult1.width; // => 5, the visual width of the string once printed to the terminal