§ Quick Take

import { strict as assert } from "assert";
import offset from "ranges-offset";

assert.deepEqual(
  offset(
    [
      [3, 5],
      [8, 7],
    ],
    10
  ),
  [
    [13, 15],
    [18, 17],
  ]
);

// ranges are empty, nothing happens:
assert.deepEqual(offset(null, 10), null);

// if input does not resemble ranges, nothing happens:
assert.deepEqual(offset(true, 10), true);

§ API

offset(arr, offset)
Input argumentTypeObligatory?Description
arrnull or Array of one or more arraysnoProvide an array of ranges to invert. Ranges do not have to be sorted or merged.
offsetInteger numbernoThis number will be added to each index of every range.

Output:

  • if not ranges were passed, array of one or more arrays, same input will be returned
  • ELSE, offset value will be added to each index of every range

Inputs are not mutated.

§ Purpose

For example, when working on parsed tokens, we have a value, chunk of string, but we know it starts at index X, not at zero. When we return zero-based result, receiving parties need to increment every index by X. The catch is, empty Ranges are null so Array.prototype.map() can't be used. Hence this library.

§ Changelog

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

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ranges-push 3.7.23
Gather string index ranges
📦 ranges-apply 3.2.4
Take an array of string index ranges, delete/replace the string according to them
📦 ranges-merge 5.0.4
Merge and sort string index ranges
📦 ranges-sort 3.13.4
Sort string index ranges
📦 string-range-expander 1.11.12
Expands string index ranges within whitespace boundaries until letters are met
📦 ranges-invert 2.1.50
Invert string index ranges
📦 ranges-iterate 1.1.49
Iterate a string and any changes within given string index ranges