In Harmony we should be able to make this even more beautiful using iterators 
[1]:

If we add:

String.prototype.[iterator] = function() {
    var s = this;
    return {
        index: 0,
        next: function() {
            if (this.index >= s.length) {
                throw StopIteration;
            }
            let cp = s.codePointAt(index);
            index += cp > 0xFFFF ? 2 : 1;
            return cp;
        }
    }
}

clients can write:

for (codePoint of str) {
    // do something with codePoint
}

Norbert

[1] http://wiki.ecmascript.org/doku.php?id=harmony:iterators


On Mar 16, 2012, at 17:04 , Jonas Höglund wrote:

> On Sat, 17 Mar 2012 00:23:25 +0100, Mark Davis ☕ <[email protected]>
> wrote:
> 
>> Whew, a lot of work, Norbert. Looks quite good. My one question is whether 
>> it is worth having a mechanism for iteration.
>> 
>> OLD CODE
>> for (int i = 0; i < s.length(); ++) {
>>  var x = s.charAt(i);
>>  // do something with x
>> }
>> 
>> Using your mechanism, one would write:
>> 
>> NEW CODE
>> for (int i = 0; i < s.length(); ++) {
>>  var x = s.codePointAt(i);
>>  // do something with x
>>  if (x > 0xFFFF) {
>>    ++i;
>>  }
>> }
>> 
>> In Java, for example, I *really* wish you could write:
>> 
>> DESIRED
>> 
>> for (int codepoint : s) {
>>  // do something with x
>> }
>> 
>> However, maybe this kind of iteration is rare enough in ES that it suffices
>> to document the pattern under NEW CODE.
>> 
> 
> That's the beauty of ECMAScript; it's extensible. :-)
> 
>      String.prototype.forEachCodePoint = function(fun) {
>        for (var i=0; i<s.length; i++) {
>          var x = s.codePointAt(i)
>          fun(x, s)
>          if (x > 0xFFFF) { ++i }
>        }
>      }
> 
>      "hello".forEachCodepoint(function(x) {
>        // do something with x
>      })
> 
>> Thanks for all your work!
>> 
>> 
>>> proposal for upgrading ECMAScript to a Unicode version released in this
>> century
>> 
>> This was amusing; could have said "this millennium" ;-)
>> ------------------------------
>> Mark <https://plus.google.com/114199149796022210033>
>> *
>> *
>> *— Il meglio è l’inimico del bene —*
>> **
>> 
> 
> Jonas
> _______________________________________________
> es-discuss mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/es-discuss

_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to