aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMarak <[email protected]>2020-08-23 19:22:02 -0500
committerGitHub <[email protected]>2020-08-23 19:22:02 -0500
commit4b82a164ddb321d919e2cf1ddd7eb0f1168d06c8 (patch)
treeb8a3d68a069e3e952c8ec00ea9abc2fab0b340f9 /lib
parent63d94f462e527dc7c7f5a83457d8e74c30f60c52 (diff)
parent56d7ccbce18164706447c2c67c2e87b3d0016462 (diff)
downloadfaker-4b82a164ddb321d919e2cf1ddd7eb0f1168d06c8.tar.xz
faker-4b82a164ddb321d919e2cf1ddd7eb0f1168d06c8.zip
Merge pull request #614 from mastermatt/bufix-shuffle-last-element
Bugfix random.shuffle last element.
Diffstat (limited to 'lib')
-rw-r--r--lib/helpers.js13
1 files changed, 10 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;
};