diff --git a/src/js/player.js b/src/js/player.js index 6bacd30..266f0c7 100644 --- a/src/js/player.js +++ b/src/js/player.js @@ -33,7 +33,7 @@ class APlayer { if (!this.isMultiple() && this.mode !== 'circulation' && this.mode !== 'order') { this.mode = 'circulation'; } - this.getRandomOrder(); + this.randomOrder = utils.randomOrder(this.options.music.length); if (this.options.showlrc) { this.container.classList.add('aplayer-withlrc'); @@ -348,34 +348,6 @@ class APlayer { return this.options.music.length > 1; } - /** - * get random order, using Fisher–Yates shuffle - */ - getRandomOrder (length = this.options.music.length) { - function random (min, max) { - if (max) { - max = min; - min = 0; - } - return min + Math.floor(Math.random() * (max - min + 1)); - } - function shuffle (arr) { - const length = arr.length, - shuffled = new Array(length); - for (let index = 0, rand; index < length; index++) { - rand = random(0, index); - if (rand !== index) { shuffled[index] = shuffled[rand]; } - shuffled[rand] = arr[index]; - } - return shuffled; - } - if (this.isMultiple()) { - this.randomOrder = shuffle([...Array(length)].map(function (item, i) { - return i; - })); - } - } - /** * get next random number */ @@ -423,7 +395,7 @@ class APlayer { const songListLength = this.container.querySelectorAll('.aplayer-list li').length; this.template.list.style.height = songListLength * 33 + 'px'; - this.getRandomOrder(); + this.randomOrder = utils.randomOrder(this.options.music.length); } /** diff --git a/src/js/utils.js b/src/js/utils.js index cf4a440..ecff807 100644 --- a/src/js/utils.js +++ b/src/js/utils.js @@ -65,6 +65,24 @@ const utils = { dragStart: isMobile ? 'touchstart' : 'mousedown', dragMove: isMobile ? 'touchmove' : 'mousemove', dragEnd: isMobile ? 'touchend' : 'mouseup' + }, + + /** + * get random order, using Fisher–Yates shuffle + */ + randomOrder: (length = this.options.music.length) => { + function shuffle (arr) { + for (let i = arr.length - 1; i >= 0; i--) { + const randomIndex = Math.floor(Math.random() * (i + 1)); + const itemAtIndex = arr[randomIndex]; + arr[randomIndex] = arr[i]; + arr[i] = itemAtIndex; + } + return arr; + } + return shuffle([...Array(length)].map(function (item, i) { + return i; + })); } };