Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
As a rule I see charAt/charCodeAt/length for strings as useful optimisations in well-curated performance code and anti-patterns in typical code.
They are great if you know what's in the string (i.e. you made it or "sanitised" it to take all the interesting bits out), but can get you in trouble for arbitrary user input where at some stage some fool is going to try out some fancier unicode.
spreadem=s=>{for(leti=0;i<s.length;i++)console.log(`Char at index ${i}: '${s.charAt(i)}'`);console.log(`Spread graphemes: '${[...s].join("', '")}'`);}
This is a really good point! Multi-character glyphs do mess with string iteration whether you split, spread, or loop. Trying to remember my solution to this the last time I encountered it in practice. I may have used a library to convert the strings to multi character arrays...
Good points! You could iterate through a string directly though with a for loop, accessing the character at each index!
Wow yesss! I didn't think to!
As a rule I see
charAt
/charCodeAt
/length
for strings as useful optimisations in well-curated performance code and anti-patterns in typical code.They are great if you know what's in the string (i.e. you made it or "sanitised" it to take all the interesting bits out), but can get you in trouble for arbitrary user input where at some stage some fool is going to try out some fancier unicode.
charAt
works nicely in the usual case:But get's funky when multi-char graphemes exist:
(see speakingjs.com/es5/ch24.html for a bit of background)
This is a really good point! Multi-character glyphs do mess with string iteration whether you split, spread, or loop. Trying to remember my solution to this the last time I encountered it in practice. I may have used a library to convert the strings to multi character arrays...
Omg I have not thought of this either. Multi-char graphemes really mess with my head