Skip to content

Commit f9ac7b6

Browse files
committed
It's enough to check str.length only once, not on every loop iteration
1 parent 4b67bca commit f9ac7b6

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

functions/strings/str_shuffle.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,23 @@ function str_shuffle (str) {
33
// + original by: Brett Zamir (http://brett-zamir.me)
44
// * example 1: shuffled = str_shuffle("abcdef");
55
// * results 1: shuffled.length == 6
6-
if (str == null) {
6+
if (arguments.length === 0) {
77
throw 'Wrong parameter count for str_shuffle()';
88
}
99

10+
if (str == null) {
11+
return '';
12+
}
13+
1014
str += '';
1115

12-
var newStr = '', rand;
16+
var newStr = '', rand, i = str.length;
1317

14-
while (str.length) {
15-
rand = Math.floor(Math.random() * str.length);
18+
while (i) {
19+
rand = Math.floor(Math.random() * i);
1620
newStr += str.charAt(rand);
1721
str = str.substring(0, rand) + str.substr(rand + 1);
22+
i--;
1823
}
1924

2025
return newStr;

0 commit comments

Comments
 (0)