aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/helpers.js13
-rw-r--r--test/helpers.unit.js13
2 files changed, 23 insertions, 3 deletions
diff --git a/lib/helpers.js b/lib/helpers.js
index f2b12da6..4100c766 100644
--- a/lib/helpers.js
+++ b/lib/helpers.js
@@ -194,17 +194,24 @@ var Helpers = function (faker) {
};
/**
- * takes an array and returns it randomized
+ * takes an array and randomizes it in place then returns it
+ *
+ * uses the modern version of the Fisher–Yates algorithm
*
* @method faker.helpers.shuffle
* @param {array} o
*/
self.shuffle = function (o) {
if (typeof o === 'undefined' || o.length === 0) {
- return [];
+ return o || [];
}
o = o || ["a", "b", "c"];
- for (var j, x, i = o.length-1; i; j = faker.random.number(i), x = o[--i], o[i] = o[j], o[j] = x);
+ for (var x, j, i = o.length - 1; i > 0; --i) {
+ j = faker.random.number(i);
+ x = o[i];
+ o[i] = o[j];
+ o[j] = x;
+ }
return o;
};
diff --git a/test/helpers.unit.js b/test/helpers.unit.js
index 5c8b31d5..f08be413 100644
--- a/test/helpers.unit.js
+++ b/test/helpers.unit.js
@@ -43,6 +43,19 @@ describe("helpers.js", function () {
var shuffled = faker.helpers.shuffle([]);
assert.ok(shuffled.length === 0);
});
+
+ it("mutates the input array in place", function () {
+ var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
+ var shuffled = faker.helpers.shuffle(input);
+ assert.deepEqual(shuffled, input);
+ });
+
+ it("all items shuffled as expected when seeded", function () {
+ var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
+ faker.seed(100);
+ var shuffled = faker.helpers.shuffle(input);
+ assert.deepEqual(shuffled, ["b", "e", "a", "d", "j", "i", "h", "c", "g", "f"]);
+ });
});
describe("slugify()", function () {