ranges-iterate1.1.48

Iterate a string and any changes within given string index ranges

§ 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:
iterate(
  "abcdefghij",
  [[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.

§ API

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

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 ranges-ent-decode 2.1.3
Recursive HTML entity decoding for Ranges workflow
📦 ranges-crop 2.1.3
Crop array of ranges when they go beyond the reference string's length
📦 ranges-invert 2.1.49
Invert string index ranges
📦 ranges-push 3.7.22
Gather string index ranges
📦 ranges-sort 3.13.3
Sort string index ranges
📦 ranges-process-outside 2.2.35
Iterate string considering ranges, as if they were already applied
📦 ranges-merge 5.0.3
Merge and sort string index ranges