§ Quick Take

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

// Ranges in the following example "punches out" a "hole" from `a` to `g`
// (included), replacing it with `xyz`. That's what gets iterated.

const gathered = [];

// a callback-based interface:
  [[0, 7, "xyz"]],
  ({ i, val }) => {
    gathered.push(`i = ${i}; val = ${val}`);

assert.deepEqual(gathered, [
  "i = 0; val = x",
  "i = 1; val = y",
  "i = 2; val = z",
  "i = 3; val = h",
  "i = 4; val = i",
  "i = 5; val = j",

§ Quick Take

It iterates all characters in a string, as if given ranges were already applied.

Sometimes certain operations on a string aren't really composable — sometimes we want to traverse the string as if ranges were applied, as if we already had the final result.


iterate(str, ranges, cb, [offset])

In other words, this library gives you a synchronous function (exported as a default) and you must feed three obligatory arguments and fourth, optional (marked with square brackets).

Input argumentTypeObligatory?Description
strstringyesThe input string we are operating on
rangesnull or array of zero or more arrays (ranges)yesThe ranges gathered so far
cbSomething falsy or a functionyesCallback function to be able to consume the indexes and character values
offsetString index, a natural numbernoYou can cut corners and start operations later in the string

§ Changelog

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

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ranges-offset 1.0.3
Increment or decrement each index in every range
📦 ranges-regex 3.0.3
Integrate regex operations into Ranges workflow
📦 ranges-crop 3.0.2
Crop array of ranges when they go beyond the reference string's length
📦 ranges-is-index-within 1.16.0
Checks if index is within any of the given string index ranges
📦 ranges-process-outside 3.0.2
Iterate string considering ranges, as if they were already applied
📦 ranges-merge 6.2.0
Merge and sort string index ranges
📦 ranges-apply 4.0.2
Take an array of string index ranges, delete/replace the string according to them