Can someone please help me better understand the design decision of making JavaScript strings iterable in ES2015? Most iterables represent collections of other things: Array, Set, Map, Generator (kinda sorta). A string can only be a collection of strings (well, Unicode codepoints). Thus if you want a function to either accept a collection of strings (e.g. Set of strings or a generator that yields strings) or a single string, there’s no way to differentiate the user’s intent. Did she mean a single string or an iterable of codepoints? Iterating over characters seems like a corner case compared to passing around collections of strings. My inclination in this case would be to special-case string parameters when the (intended) type is string ∪ Iterable<string>.
function deleteDocuments(ids /* string or Iterable<string> */) {
if('string' === typeof ids) {
deleteSingleDocById(ids);
} else {
for(let id of ids) {
deleteSingleDocById(id);
}
}
}
What am I missing?
This is really the continuation of a principle that preceded ES2015/ES6. Since the release of Internet Explorer 8, every browser has allowed you to loop over the contents of Arrays and Strings using the same syntax.
var array = ['a', 'b', 'c'];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
var string = 'abc';
for (var i = 0; i < string.length; i++) {
console.log(string[i]);
}
Strings were already "array-like"; they fulfilled the implicit array iteration protocol (of having .length and indexed properties), and each character was already treated as its own string when looked up. We could argue over whether that was the right choice, but it's distant history at this point. It would have been a weird divergence of behaviour if, post-ES2015, you were expected to use different syntaxes for iterating over Arrays and Strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With