UNPKG

string-convert-indexes

Version:

Convert between native JS string character indexes and grapheme-count-based indexes

12 lines (10 loc) 2.48 kB
/** * @name string-convert-indexes * @fileoverview Convert between native JS string character indexes and grapheme-count-based indexes * @version 6.0.22 * @author Roy Revelt, Codsen Ltd * @license MIT * {@link https://codsen.com/os/string-convert-indexes/} */ import{traverse as d}from"ast-monkey-traverse";import v from"grapheme-splitter";var g="6.0.22";var E=g;function f(o,i,t){function a(r){return!(!["string","number"].includes(typeof r)||typeof r=="string"&&!/^\d*$/.test(r)||typeof r=="number"&&(!Number.isInteger(r)||r<0))}function c(r,n){let u=0,e=0;for(let p=0,m=r.length;p<m;p++){if(e+=r[p].length,n>=u&&n<e)return p;u+=r[p].length}throw new Error(`string-convert-indexes: [THROW_ID_05] the "indexes" value, ${t}, is not covered by graphemes length!`)}function l(r,n){if(n>=r.length)throw new Error(`string-convert-indexes: [THROW_ID_06] the index to convert, ${n}, is not covered by graphemes length!`);return r.slice(0,n).join("").length}if(typeof i!="string"||!i)throw new TypeError(`string-convert-indexes: [THROW_ID_01] the first input argument, input string, must be a non-zero-length string! Currently it's: ${typeof i}, equal to: ${i}`);if(t===0)return 0;if(t==="0")return"0";let s=new v().splitGraphemes(i);if(["string","number"].includes(typeof t)){if(a(t))return o==="u"?typeof t=="string"?String(l(s,+t)):l(s,+t):typeof t=="string"?String(c(s,+t)):c(s,+t);throw new Error(`string-convert-indexes: [THROW_ID_02] the second input argument, "indexes" is not suitable to describe string index - it was given as ${JSON.stringify(t,null,4)} (${typeof t})`)}else{if(t&&typeof t=="object")return o==="u"?d(t,(r,n,u)=>{let e=n!==void 0?n:r;if(["string","number"].includes(typeof e)){if(a(e))return typeof e=="string"?String(l(s,+e)):l(s,+e);throw new Error(`string-convert-indexes: [THROW_ID_03] bad value was encountered, ${JSON.stringify(e,null,4)}, its path is ${u.path}`)}return e}):d(t,(r,n,u)=>{let e=n!==void 0?n:r;if(["string","number"].includes(typeof e)){if(a(e))return typeof e=="string"?String(c(s,+e)):c(s,+e);throw new Error(`string-convert-indexes: [THROW_ID_04] bad value was encountered, ${JSON.stringify(e,null,4)}, its path is ${u.path}`)}return e});throw new Error(`string-convert-indexes: [THROW_ID_07] the first input argument, a source string should be a string but it was given as ${i}, type ${typeof i}`)}}function I(o,i){return f("n",o,i)}function T(o,i){return f("u",o,i)}export{I as nativeToUnicode,T as unicodeToNative,E as version};