string-dashes
Version:
Comprehensive, HTML-entities-aware tool to typographically-correct the dashes and hyphens
11 lines (9 loc) • 2.74 kB
JavaScript
/**
* @name string-dashes
* @fileoverview Comprehensive, HTML-entities-aware tool to typographically-correct the dashes and hyphens
* @version 1.3.0
* @author Roy Revelt
* @license MIT
* {@link https://codsen.com/os/string-dashes/}
*/
import{rApply as D}from"ranges-apply";import{left as v,right as O}from"string-left-right";import{isQuote as V,isLetter as p,rawNDash as m,rawMDash as c,isNumberChar as l,isCurrencyChar as d,isWhitespaceChar as f,isUppercaseLetter as h}from"codsen-utils";var b="1.3.0";var A=b,y={convertEntities:!1,convertDashes:!0};function x(e,t){if(typeof e!="string")throw new Error(`string-dashes/convertOne(): [THROW_ID_01] first input argument should be string! It's been passed as ${e} (its typeof ${typeof e})`);if(typeof t!="object"||Array.isArray(t))throw new Error(`string-dashes/convertOne(): [THROW_ID_02] options object should be a plain object. It has was passed as ${JSON.stringify(t,null,4)} (its typeof is ${typeof t})`);if(!Number.isInteger(t.from)||t.from<0)throw new Error(`string-dashes/convertOne(): [THROW_ID_03] options objects key "to", a starting string index, should be a natural number! It was given as ${t.from} (its typeof is ${typeof t.from})`);if(t.from>=e.length)throw new Error(`string-dashes/convertOne(): [THROW_ID_04] opts.from is beyond str length! opts.from was passed as ${t.from} and str.length is ${e.length}`);let{from:n=0,to:s,value:r,convertEntities:o,convertDashes:u,offsetBy:g}={...y,...t};Number.isInteger(s)||(s=n+1);let i=[];if(!u)return null;if((r&&["-",c].includes(r)||s===n+1&&["-",c].includes(e[n]))&&(e[n-1]&&e[s]&&l(e[n-1])&&l(e[s])||!p(e[n-2])&&!p(e[s+1])&&h(e[n-1])&&h(e[s]))&&i.push([n,s,o?"–":m]),r&&["-",m].includes(r)||s===n+1&&["-",m].includes(e[n]))if(e[n-1]&&e[s]&&f(e[n-1])&&f(e[s])){let $=null,a=null;e[n-2]&&(e[n-2].trim()?$=n-2:$=v(e,n)),e[s+1]&&(e[s+1].trim()?a=s+1:a=O(e,n)),l(e[$])&&l(e[a])||l(e[$])&&d(e[a])||d(e[$])&&l(e[a])?i.push([n,s,o?"–":m]):i.push([n,s,o?"—":c])}else e[n-1]&&p(e[n-1])&&e[s]&&V(e[s])&&i.push([n,s,o?"—":c]);return i.length?i:null}function j(e,t){if(typeof e!="string")throw new Error(`string-dashes: [THROW_ID_10] first input argument should be string! It's been passed as ${e} (its typeof ${typeof e})`);if(t&&(typeof t!="object"||Array.isArray(t)))throw new Error(`string-dashes: [THROW_ID_11] options object should be a plain object! It was passed as ${JSON.stringify(t,null,4)} (its typeof is ${typeof t})`);if(!e)return{result:e,ranges:null};let n=[],s={...y,...t},r=e.length;for(let o=0;o<r;o++){s.from=o,s.offsetBy=g=>{o+=g};let u=x(e,s);Array.isArray(u)&&u.length&&(n=n.concat(u))}return{result:D(e,n),ranges:n}}export{j as convertAll,x as convertOne,y as defaults,A as version};