Looking at the description of both substr() and substring(), I'd imagine "they" wanted to get rid of substr() and some of its more arcane behaviors and introduced a new method to replace it, it wasn't just a name change.
For extra fun, just look at this amazing bit of TFM:
Although you are encouraged to avoid using substr(), there is no trivial way to migrate substr() to either slice() or substring() in legacy code without essentially writing a polyfill for substr(). For example, str.substr(a, l), str.slice(a, a + l), and str.substring(a, a + l) all have different results when str = "01234", a = 1, l = -2 — substr() returns an empty string, slice() returns "123", while substring() returns "0". The actual refactoring path depends on the knowledge of the range of a and l.
Actually substr handles that internally already, if you set a max that's longer than value it just returns value. In the end you'd most likely be just fine just using substr without wrapping it in a function.
[The .substr call in the following code is marked with strikethrough.]
const onStringNum_S = function (value, max) {
let temp = 0
for (let i = 0; i < value.length; i++) {
temp++
if (temp > max) {
return value.substr(0, i)
}
}
return value
}
To me, it’s a matter of patterns and habits. It’s always less ambiguous to use explicit scoping boundaries, if applicable in the given language. Omitting them can occasionally lead to subtle errors. I always use them as a rule, simply to sidestep that entire category of bugs.
104
u/Bulji Feb 10 '23
equivalent to?
14
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Feb 10 '23
Image Transcription: Code
[The
.substrcall in the following code is marked with strikethrough.]I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
18
u/Alphatism Feb 10 '23
Wouldn't this just be
6
u/Cybasura Feb 10 '23
The bad code is the function name
I can at least see why they did it this way, probably the guard clause is to ensure that the value does not go beyond the max value
3
u/reddit_user_25 Feb 10 '23
"I made it work, now I need a budget for efficiency improvements."
2
u/trehinkarsalt Feb 10 '23
Not that bad actually. If that is your biggest problem you are lucky =)
1
u/himalayangoat Feb 10 '23
Why do I always fear I'll see some of my old code here?
1
u/Aromatic_Prior_1371 Feb 11 '23
let
-9
u/[deleted] Feb 10 '23
[removed] — view removed comment