dotcypress / runes

✂️ Unicode-aware JS string splitting
MIT License
226 stars 13 forks source link

Document the difference between rune .substr() and String.prototype.substring() #6

Open johnsonjo4531 opened 4 years ago

johnsonjo4531 commented 4 years ago

I was expecting runes.substr functionality to be the same API as String.prototype.substring but there is a fundamental difference. Take for example the following code:

var runes = require("runes")

console.log("runes".substring(2,3))
console.log(runes.substr("runes", 2,3))

Which outputs:

'n'
'nes'

The reason it's so different, as you may know, is the runes.substr takes an inclusive begin index and a count (to take from that begin index) whereas the String.prototype.substring takes an inclusive begin index and an exclusive end index. Mainly it would be nice to see in the documentation that these are different API surfaces and just explain the difference or show that the runes.substr takes a count as the third param. Possibly you could add a runes.substring which is a wrapper around the other substr method that acts more like the JS API String.prototype.substring (of course this is not necessary and is just a suggestion):

var runes = require("runes")

console.log("runes".substring(2,3))
console.log(runes.substr("runes", 2,3))
console.log(substring("runes", 2,3))

// possible implmentation of substring
function substring (str, start, end) {
  if(typeof end === "number" && end <= start) {
    return '';
  } else if(typeof end === "number") { 
    return runes.substr(str, start, end - start);
  } else {
    return runes.substr(str, start);
  }
}

I will offer my time to write a pull request if you would be interested for either of these issues/proposals just let me know if you'd be interested.

johnsonjo4531 commented 4 years ago

By the way thanks for this excellent package!