ranges-invert
Version:
Invert string index ranges
12 lines (10 loc) • 2.5 kB
JavaScript
/**
* @name ranges-invert
* @fileoverview Invert string index ranges
* @version 6.0.19
* @author Roy Revelt, Codsen Ltd
* @license MIT
* {@link https://codsen.com/os/ranges-invert/}
*/
import{rMerge as h}from"ranges-merge";import{rCrop as f}from"ranges-crop";var m="6.0.19";var I=m,$={strictlyTwoElementsInRangeArrays:!1,skipChecks:!1};function x(t,n,g){if(!Array.isArray(t)&&t!==null)throw new TypeError(`ranges-invert: [THROW_ID_01] Input's first argument must be an array, consisting of range arrays! Currently its type is: ${typeof t}, equal to: ${JSON.stringify(t,null,4)}`);if(!Number.isInteger(n)||n<0)throw new TypeError(`ranges-invert: [THROW_ID_02] Input's second argument must be a natural number or zero (coming from String.length)! Currently its type is: ${typeof n}, equal to: ${JSON.stringify(n,null,4)}`);if(Array.isArray(t)&&typeof t[0]=="number"&&typeof t[1]=="number")throw new TypeError(`ranges-invert: [THROW_ID_07] The first argument should be AN ARRAY OF RANGES, not a single range! Currently arrOfRanges = ${JSON.stringify(t,null,0)}!`);if(!Array.isArray(t)||!t.filter(e=>Array.isArray(e)&&e[0]!==e[1]).length||!n)return n?[[0,n]]:null;let i={...$,...g},s=0,c;if(!i.skipChecks&&i.strictlyTwoElementsInRangeArrays&&!t.filter(e=>e).every((e,r)=>e.length!==2?(s=r,c=e.length,!1):!0))throw new TypeError(`ranges-invert: [THROW_ID_04] Because opts.strictlyTwoElementsInRangeArrays was enabled, all ranges must be strictly two-element-long. However, the ${s}th range (${JSON.stringify(t[s],null,0)}) has not two but ${c} elements!`);if(!i.skipChecks&&!t.every((e,r)=>!Number.isInteger(e[0])||e[0]<0||!Number.isInteger(e[1])||e[1]<0?(s=r,!1):!0))throw new TypeError(`ranges-invert: [THROW_ID_05] The first argument should be AN ARRAY OF ARRAYS! Each sub-array means string slice indexes. In our case, here ${s+1}th range (${JSON.stringify(t[s],null,0)}) does not consist of only natural numbers!`);let u;i.skipChecks?u=t.filter(e=>e[0]!==e[1]):u=h(t.filter(e=>e[0]!==e[1]));let y=u.reduce((e,r,p,o)=>{let a=[];p===0&&o[0][0]!==0&&a.push([0,o[0][0]]);let l=p<o.length-1?o[p+1][0]:n;if(r[1]!==l){if(i.skipChecks&&r[1]>l)throw new TypeError(`ranges-invert: [THROW_ID_08] The checking (opts.skipChecks) is off and input ranges were not sorted! We nearly wrote range [${r[1]}, ${l}] which is backwards. For investigation, whole ranges array is:
${JSON.stringify(o,null,0)}`);a.push([r[1],l])}return e.concat(a)},[]);return f(y,n)}export{$ as defaults,x as rInvert,I as version};