Installation
Quick Take
Examples
- Delete a range by omitting its replacement value
- Insert text with a zero-width range
- Apply ranges whose indexes arrive as numeric strings
- Gather progress while applying multiple ranges
API — rApply()
The main function rApply() is imported like this:
It’s a function which takes three input arguments:
| Input argument | Type | Obligatory | Description |
|---|---|---|---|
strType: String Obligatory: yes | |||
str | String | yes | Provide an array of ranges to invert. Ranges do not have to be sorted or merged. |
rangesArrayType: Array of zero or more arrays — OR — nullObligatory: yes | |||
rangesArray | Array of zero or more arrays — OR — null | yes | Ranges to apply onto the string |
progressFnType: Function or something falsy Obligatory: no | |||
progressFn | Function or something falsy | no | Provide a callback function to report the progress — numbers 0 to 100 will be fed into it as the program advances. |
Function will return an amended string.
TIP: 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.
API — version
You can import version:
API — types
This package is written in TypeScript and exports the following types:
| Type | Description |
|---|---|
RangesInputType: RangesInput | |
RangesInput | What rApply() accepts as its second argument — a single Range, or Ranges. |
RangeType: Range | |
Range | A single range, re-exported from ranges-merge. |
RangesType: Ranges | |
Ranges | Zero or more Ranges, or null, re-exported from ranges-merge. |
import type { Range, Ranges, RangesInput } from "ranges-apply";
The algorithm
The program array.reduce()s your given ranges array, slicing the input string accordingly. If given ranges is not array but null (meaning absence of ranges), the same string is returned.
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.