ranges-apply3.2.4

Take an array of string index ranges, delete/replace the string according to them

§ Quick Take

import { strict as assert } from "assert";
import applyR from "ranges-apply";

const oldString = `The quick brown fox jumps over the lazy dog.`;
const ranges = [
  [4, 19, "bad grey wolf"],
  [35, 43, "little Red Riding Hood"],
];
assert.equal(
  applyR(oldString, ranges),
  "The bad grey wolf jumps over the little Red Riding Hood."
);

§ Purpose

It takes the source string and the amendments described by Ranges and produces a new string.

§ API

applyR(
  inputString,
  rangesArray,
  [progressFn]
)
Input argumentTypeObligatory?Description
inputStringStringyesProvide an array of ranges to invert. Ranges do not have to be sorted or merged.
rangesArrayArray of zero or more arrays - OR - nullyesRanges to apply onto the string
progressFnFunction or something falsynoProvide a callback function to report the progress - numbers 0 to 100 will be fed into it as the program advances.

§ API - Output

Function returns an amended string.

Check out ranges-push which helps to manage the rangesArray. It has methods to add and retrieve the ranges. Also, it helps in cases where ranges overlap and helps to maintain the sorting order.

§ The algorithm

We array.reduce() your given ranges array, slicing the input string accordingly. If given ranges is not array but null (meaning absence of ranges), same string is returned.

The main thing is unit tests and edge case scenarios. Also, fancy optional features (upcoming) like using character enumeration counting emoji as one character.

§ In our case

Originally this library was part of email-comb, where we traversed HTML as a string and compiled an array of things to delete or replace later, in one go. The performance was important, so it was not a good idea to delete/replace things on the spot because each deletion slowed down the process. Instead, we traversed the string, compiled this to-do array, then did the deletion/replacement on the whole thing, once. This appears to be the fastest way.

We're going to use this library in all our HTML processing libraries who work on HTML as on string, without parsing it.

§ 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-merge 5.0.4
Merge and sort string index ranges
📦 ranges-sort 3.13.4
Sort string index ranges
📦 ranges-offset 1.0.2
Increment or decrement each index in every range
📦 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-is-index-within 1.15.3
Checks if index is within any of the given string index ranges