Permalink
Browse files

use an iterator

  • Loading branch information...
1 parent a3b40e2 commit 07fcbe71a2a5f06afc071d32cf6e433c2beeac1c @peter-leonov committed Feb 14, 2012
Showing with 12 additions and 6 deletions.
  1. +12 −6 src/modules/array-randomize.js
@@ -20,12 +20,16 @@ Array.prototype.random = function (n)
if (n <= 0)
return []
- var len = this.length
-
if (n == 1)
- return [this[(random() * len) >> 0]]
+ return [this[(random() * this.length) >> 0]]
- var copy = this.slice()
+ // n > 1
+ return this.slice().fetchRandom(n)
+}
+
+Array.prototype.fetchRandom = function (n)
+{
+ var len = this.length
if (n > len)
n = len
@@ -36,11 +40,13 @@ Array.prototype.random = function (n)
{
var r = (random() * len) >> 0
- res[i] = copy[r]
+ res[i] = this[r]
len--
- copy[r] = copy[len]
+ this[r] = this[len]
}
+ this.length = len
+
return res
}

0 comments on commit 07fcbe7

Please sign in to comment.