5000000 random inserts on an empty string, resulting in the string of size 6M chars long: Rope took 5610 ms. 0.001122 ms per iteration, 891k iterations per second JS toString took 3463 ms. 0.003463 ms per iteration, 288k iterations per second (Tested on node v10.13.0)
Ropes have insertion and deletion time of O(|s| * log(N)) where |s| is the length of the inserted / deleted region N is the length of the string
npm install jumprope
Rope = ;var r = 'initial string';r; // Insert 'some text' at position 4 in the stringr; // Delete 9 characters from the string at position 4console;
String contains: 'initial string' length: 14
new Rope([initial text])
Create a new rope, optionally with the specified initial text.
Rope = ;var r = ; // Create a new Ropevar r = 'str'; // Create a new Rope with initial string 'str'
Insert text into the rope at the specified position.
r; // Insert 'some text' at position 4. Position must be inside the string.
r.del(position, count, [callback])
count characters from the rope at
position. Delete can optionally take a callback, which is called with the deleted substring.
r; // Delete 10 characters at position 4r; // Delete 10 characters, and print them out.
Iterate through the rope. The callback will be passed the whole string, a few characters at a time. This is the fastest way to read the string if you want to write it over a network stream, for example.
// Print the string out, a few characters at a time.r
Internally, this just calls
.join's the result.
Get the number of characters in the rope.
r; // Delete the last 4 characters in the string.
Get a substring of the string. Kinda like splice, I guess. Maybe I should copy the JS API.
console; // Print out 10 characters from position 4 onwards.
Of course, when your strings are that small it doesn't matter that much how you're using them.
Once your strings get long, jumpropes become a lot faster.
MIT licensed, so do what you want with it.
Thanks to Ben Weaver for his node closure library