From bbfe040c41748bc67b0264733a71580b1d7f0378 Mon Sep 17 00:00:00 2001 From: gnysek Date: Wed, 16 Nov 2022 15:45:46 +0100 Subject: [PATCH] array_shuffle - optimization of duplicated code Optimized new functions to keep code in DRY principle, as there was only 1 different code line between `array_shuffle()` (`ret = _array.slice();`) and `array_shuffle_ext()` (`ret = _array;`), and other 24 were same. --- scripts/yyVariable.js | 59 +++++++++++++++---------------------------- 1 file changed, 20 insertions(+), 39 deletions(-) diff --git a/scripts/yyVariable.js b/scripts/yyVariable.js index c2af6017..3ba08e1a 100644 --- a/scripts/yyVariable.js +++ b/scripts/yyVariable.js @@ -682,27 +682,27 @@ function array_sort( _array, _typeofSort ) } // end else } // end array_sort -function array_shuffle( _array ) +function array_shuffle_common( _array, _return_copy ) { var ret = undefined; if (Array.isArray(_array)) { - ret = _array.slice(); - var currentIndex = ret.length, temporaryValue, randomIndex; + ret = (_return_copy === true) ? _array.slice() : _array; - // While there remain elements to shuffle... - while (0 !== currentIndex) { + var currentIndex = ret.length, temporaryValue, randomIndex; - // Pick a remaining element... - randomIndex = Math.floor(Math.random() * currentIndex); - currentIndex -= 1; + // While there remain elements to shuffle... + while (0 !== currentIndex) { - // And swap it with the current element. - temporaryValue = ret[currentIndex]; - ret[currentIndex] = ret[randomIndex]; - ret[randomIndex] = temporaryValue; - } + // Pick a remaining element... + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex -= 1; + // And swap it with the current element. + temporaryValue = ret[currentIndex]; + ret[currentIndex] = ret[randomIndex]; + ret[randomIndex] = temporaryValue; + } } // end if else { @@ -711,33 +711,14 @@ function array_shuffle( _array ) return ret; } // end array_shuffle -function array_shuffle_ext( _array ) +function array_shuffle( _array ) { - var ret = undefined; - if (Array.isArray(_array)) { - - ret = _array; - var currentIndex = ret.length, temporaryValue, randomIndex; - - // While there remain elements to shuffle... - while (0 !== currentIndex) { - - // Pick a remaining element... - randomIndex = Math.floor(Math.random() * currentIndex); - currentIndex -= 1; - - // And swap it with the current element. - temporaryValue = ret[currentIndex]; - ret[currentIndex] = ret[randomIndex]; - ret[randomIndex] = temporaryValue; - } - + return array_shuffle_common( _array, true); +} // end array_shuffle - } // end if - else { - yyError( "argument0 is not an array"); - } // end else - return ret; +function array_shuffle_ext( _array ) +{ + return array_shuffle_common( _array, false); } // end array_shuffle_ext @@ -2501,4 +2482,4 @@ function variable_struct_remove( _id, _var) } // end if } // end for } // end if -} \ No newline at end of file +}