@visulima/string
Version:
Functions for manipulating strings.
2 lines (1 loc) • 1.58 kB
JavaScript
var g=Object.defineProperty;var h=(t,i)=>g(t,"name",{value:i,configurable:!0});import{getStringTruncatedWidth as l}from"./get-string-truncated-width.mjs";import{slice as d}from"./slice.mjs";var b=Object.defineProperty,p=h((t,i)=>b(t,"name",{value:i,configurable:!0}),"h");const u="…",y=3,f=p((t,i,e=!1)=>{if(t.charAt(i)===" ")return i;const r=e?1:-1,a=Math.min(y,e?t.length-i:i);for(let c=1;c<=a;c++){const n=i+c*r;if(t.charAt(n)===" ")return n}return i},"findNearestSpace"),T=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=u,position:a="end",preferTruncationOnSpace:c=!1}=e;let n=e.ellipsisWidth??r===u?1:void 0;if(n===void 0&&(n=l(r,{...e.width,ellipsis:"",ellipsisWidth:0,limit:Number.POSITIVE_INFINITY}).width),i===1&&n===1)return r;if(i===1)return"";const{width:o}=l(t,{...e.width,ellipsis:r,ellipsisWidth:n});if(o<=i)return t;switch(a){case"end":{if(c){const s=f(t,i-1);return d(t,0,s,{width:e.width})+r}return d(t,0,i-n,{width:e.width})+r}case"middle":{const s=Math.floor(i/2);if(c){const w=f(t,s),m=f(t,o-(i-s)+1,!0);return d(t,0,w)+r+d(t,m,o).trim()}return d(t,0,s,{width:e.width})+r+d(t,o-(i-s)+n,o,{width:e.width})}case"start":{if(c){const s=f(t,o-i+1,!0);return r+d(t,s,o).trim()}return r+d(t,o-i+n,o,{width:e.width})}default:throw new Error(`Invalid position: expected 'start', 'middle' or 'end', got '${a}'`)}},"truncate");export{T as truncate};