On Jan 3, 2012, at 15:46 , Greg Smith wrote:

> What is the use case for .repeat? Trying to imagine some code where I'd need 
> it so I can get a feel for how it should work.

So beauty alone does not count? ;-)

It’s true – there are not a lot of use cases for Array.repeat().

But I keep thinking that there should be a way to create an array of a given 
length *with* content in it. Rationale: such an array is nice to have as a 
starting point for a transformation via Array.prototype.map() or an array 
comprehension [1]. How about the following?

    Array.range = function (start, end) {
        if (arguments.length < 1 || arguments.length > 2) {
            throw new TypeError("Need one or two arguments");
        }
        if (arguments.length === 1) {
            end = start;
            start = 0;
        }
        var result = [];
        for(var i=start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

Interaction:

    > Array.range(4)
    [ 0, 1, 2, 3 ]
    > Array.range(4).map(function () { return "*" })
    [ '*', '*', '*', '*' ]

I’m not yet sure how many use cases there are (suggestions welcome), but it 
does fill a hole (IIRC, Python has something similar).

TODO: This method probably makes more sense as an iterator (e.g. implemented 
via a generator). Then one could even omit the upper limit and produce an 
unlimited sequence.

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

-- 
Dr. Axel Rauschmayer
a...@rauschma.de

home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com



_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to