@visulima/string
Version:
Functions for manipulating strings.
2 lines (1 loc) • 1.75 kB
JavaScript
;var m=Object.defineProperty;var a=(t,i)=>m(t,"name",{value:i,configurable:!0});Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const h=require("./get-string-truncated-width.cjs"),c=require("./slice.cjs");var b=Object.defineProperty,p=a((t,i)=>b(t,"name",{value:i,configurable:!0}),"h");const f="…",T=3,u=p((t,i,e=!1)=>{if(t.charAt(i)===" ")return i;const r=e?1:-1,l=Math.min(T,e?t.length-i:i);for(let d=1;d<=l;d++){const n=i+d*r;if(t.charAt(n)===" ")return n}return i},"findNearestSpace"),v=p((t,i,e={})=>{if(typeof t!="string")throw new TypeError(`Expected \`input\` to be a string, got ${typeof t}`);if(typeof i!="number")throw new TypeError(`Expected \`limit\` to be a number, got ${typeof i}`);if(t===""||i<=0)return"";t=t.normalize("NFC");const{ellipsis:r=f,position:l="end",preferTruncationOnSpace:d=!1}=e;let n=e.ellipsisWidth??r===f?1:void 0;if(n===void 0&&(n=h.getStringTruncatedWidth(r,{...e.width,ellipsis:"",ellipsisWidth:0,limit:Number.POSITIVE_INFINITY}).width),i===1&&n===1)return r;if(i===1)return"";const{width:s}=h.getStringTruncatedWidth(t,{...e.width,ellipsis:r,ellipsisWidth:n});if(s<=i)return t;switch(l){case"end":{if(d){const o=u(t,i-1);return c.slice(t,0,o,{width:e.width})+r}return c.slice(t,0,i-n,{width:e.width})+r}case"middle":{const o=Math.floor(i/2);if(d){const w=u(t,o),g=u(t,s-(i-o)+1,!0);return c.slice(t,0,w)+r+c.slice(t,g,s).trim()}return c.slice(t,0,o,{width:e.width})+r+c.slice(t,s-(i-o)+n,s,{width:e.width})}case"start":{if(d){const o=u(t,s-i+1,!0);return r+c.slice(t,o,s).trim()}return r+c.slice(t,s-i+n,s,{width:e.width})}default:throw new Error(`Invalid position: expected 'start', 'middle' or 'end', got '${l}'`)}},"truncate");exports.truncate=v;