`str.startswith()` with start position
phfaist opened this issue · 1 comments
Thanks first of all for this great project!
It appears that the startswith()
method of strings cannot be used with a starting position parameter (cf str.startswith()
). If I try to transcrypt the following code, instead of getting both times "Yes!" I get first "Yes" and then "No".
if "abc".startswith("a", 0):
print("1 - Yes!")
else:
print("1 - No :(")
if "abc".startswith("b", 1):
print("2 - Yes!")
else:
print("2 - No :(")
I used the commands:
> transcrypt --parent .none teststartswith.py
> echo '{"type":"module"}' >__target__/package.json
> node __target__/teststartswith.js
1 - Yes!
2 - No :(
Transcrypt version:
name : transcrypt
version : 3.9.0
Digging in the generated (nonminified) JS runtime code, I found that the String.prototype.startswith
method does not seem to implement the start parameter. Would you consider adding support for it? It would not appear to add significant complexity, and it can avoid breaking existing python code that depends on this behavior (as I experienced). A possible implementation suggestion could be something along the lines of:
String.prototype.startswith = function (prefix, start) {
var pos_start = (typeof start == 'undefined' ? 0 : start);
if (prefix instanceof Array) {
for (var i=0;i<prefix.length;i++) {
if (this.substr(pos_start, prefix[i].length) == prefix [i]) {
return true;
}
}
} else {
return (this.substr(pos_start, prefix.length) == prefix);
}
return false;
};
Additionally, it might be desirable to implement the end parameter of python's str.startswith()
, too.
Incidentally, the existing implementation of startswith()
appears to use the check this.indexOf(prefix) == 0
. Wouldn't this be inefficient on long strings, as the indexOf
algorithm potentially searches through the full string for the substring prefix
, or am I missing anything?
I just created a PR that adds the start
and end
arguments to the Transcrypt version for both startswith
and endswith
methods.
I didn't address the potential efficiency issues of using indexOf
vs a direct comparison with a substr
or slice
though.