Quick Take

import { strict as assert } from "assert";
import { rInvert } from "ranges-invert";

      [3, 5],
      [5, 7],
    9 // string length needed to set the boundary
    [0, 3],
    [7, 9],


rInvert(arr, strLen, [opts])
Input argument Type Obligatory? Description
arrOfRanges Array of zero or more arrays yes Provide an array of ranges to invert. Ranges do not have to be sorted or merged.
strLen Integer number yes Algorithm needs to know the length of the reference string to calculate the inverted last slice's ending index.
opts Plain object no Optional options go here.

Output: null OR array of zero or more arrays (so-called ranges) where each consists of two or more natural number (or zero) indexes.

This package does not mutate the input array, instead it creates and returns a new array with ranges inverted.

Options object

options object's key Type Obligatory? Default Description
strictlyTwoElementsInRangeArrays Boolean no false If set to true, all ranges must have two and only two elements, otherwise an error will be thrown. For example, input being [ [1, 2, 'zzz'] ] would throw (because of 3 elements), as well as [ ['a'] ] (1 element).
skipChecks Boolean no false If set to true, no checks will be performed. It's handy to cut corners for perf reasons when you know input ranges are clean.


See it in the monorepo opens in a new tab, on GitHub.


To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.


MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 ranges-push 6.0.1
Gather string index ranges
📦 ranges-iterate 3.0.1
Iterate a string and any changes within given string index ranges
📦 ranges-is-index-within 3.0.1
Checks if index is within any of the given string index ranges
📦 ranges-merge 8.0.1
Merge and sort string index ranges
📦 ranges-regex 5.0.1
Integrate regex operations into Ranges workflow
📦 ranges-apply 6.0.1
Take an array of string index ranges, delete/replace the string according to them
📦 ranges-crop 5.0.1
Crop array of ranges when they go beyond the reference string's length