Suggestion: Array.prototype.repeat

Mariusz Nowak medikoo+mozilla.org at medikoo.com
Mon Jan 2 12:56:47 PST 2012


I like it, it indeed looks very logical, however it's a bit controversial
that we need to create temporary array object to get one that we want.
Function (not method) that returns generated array may make more sense,
currently I'm using something like that:

var slice = Array.prototype.slice;

Array.generate = function (length, fill) {
	var arr, l;
	length = length >>> 0;
	if (arguments.length < 2) {
		throw new TypeError("Cannot generarte an array without provided fill.");
	}
	arr = slice.call(arguments, 1, 1 + length);
	while ((l = arr.length) < length) {
		arr = arr.concat(arr.slice(0, length - l));
	}
	return arr;
};

( https://github.com/medikoo/es5-ext/blob/master/lib/Array/generate.js )

-- 
Mariusz Nowak
https://github.com/medikoo/


rauschma wrote:
> 
> 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
> 
> 
> 
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
> 
> 


-----
Mariusz Nowak

https://github.com/medikoo
-- 
View this message in context: http://old.nabble.com/Suggestion%3A-Array.prototype.repeat-tp33067649p33068241.html
Sent from the Mozilla - ECMAScript 4 discussion mailing list archive at Nabble.com.



More information about the es-discuss mailing list