§ Quick Take

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

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

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

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

§ API

rOffset(rangesArr, offset)
Input argumentTypeObligatory?Description
arrnull or Array of one or more arrays (Ranges)noProvide 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 GitHub.

§ Contributing

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.

§ Licence

MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 ranges-push 5.0.6
Gather string index ranges
📦 ranges-apply 5.0.6
Take an array of string index ranges, delete/replace the string according to them
📦 ranges-merge 7.0.6
Merge and sort string index ranges
📦 ranges-sort 4.0.6
Sort string index ranges
📦 string-range-expander 2.0.6
Expands string index ranges within whitespace boundaries until letters are met
📦 ranges-ent-decode 4.0.6
Recursive HTML entity decoding for Ranges workflow
📦 ranges-regex 4.0.6
Integrate regex operations into Ranges workflow