Suggestion: Array.prototype.repeat

Axel Rauschmayer axel at rauschma.de
Mon Jan 2 10:49:15 PST 2012


Array.prototype.repeat seems like a logical dual to String.prototype.repeat:
    http://wiki.ecmascript.org/doku.php?id=harmony:string.prototype.repeat

Implementation:

    Array.prototype.repeat = function (times) {
        var result = [];
        var len = this.length;
        var resultLen = len * times;
        for(var i = 0; i < resultLen; i++) {
            result.push(this[i % len]);
        }
        return result;
    }

In use:

    $ [1,2,3].repeat(3)
    [ 1,  2,  3,  1,  2,  3,  1,  2,  3 ]

-- 
Dr. Axel Rauschmayer
axel at rauschma.de

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





More information about the es-discuss mailing list