Skip to content

Commit c590dd4

Browse files
committed
move getRandomOrder to utils
1 parent 532dddc commit c590dd4

2 files changed

Lines changed: 20 additions & 30 deletions

File tree

src/js/player.js

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class APlayer {
3333
if (!this.isMultiple() && this.mode !== 'circulation' && this.mode !== 'order') {
3434
this.mode = 'circulation';
3535
}
36-
this.getRandomOrder();
36+
this.randomOrder = utils.randomOrder(this.options.music.length);
3737

3838
if (this.options.showlrc) {
3939
this.container.classList.add('aplayer-withlrc');
@@ -348,34 +348,6 @@ class APlayer {
348348
return this.options.music.length > 1;
349349
}
350350

351-
/**
352-
* get random order, using Fisher–Yates shuffle
353-
*/
354-
getRandomOrder (length = this.options.music.length) {
355-
function random (min, max) {
356-
if (max) {
357-
max = min;
358-
min = 0;
359-
}
360-
return min + Math.floor(Math.random() * (max - min + 1));
361-
}
362-
function shuffle (arr) {
363-
const length = arr.length,
364-
shuffled = new Array(length);
365-
for (let index = 0, rand; index < length; index++) {
366-
rand = random(0, index);
367-
if (rand !== index) { shuffled[index] = shuffled[rand]; }
368-
shuffled[rand] = arr[index];
369-
}
370-
return shuffled;
371-
}
372-
if (this.isMultiple()) {
373-
this.randomOrder = shuffle([...Array(length)].map(function (item, i) {
374-
return i;
375-
}));
376-
}
377-
}
378-
379351
/**
380352
* get next random number
381353
*/
@@ -423,7 +395,7 @@ class APlayer {
423395
const songListLength = this.container.querySelectorAll('.aplayer-list li').length;
424396
this.template.list.style.height = songListLength * 33 + 'px';
425397

426-
this.getRandomOrder();
398+
this.randomOrder = utils.randomOrder(this.options.music.length);
427399
}
428400

429401
/**

src/js/utils.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,24 @@ const utils = {
6565
dragStart: isMobile ? 'touchstart' : 'mousedown',
6666
dragMove: isMobile ? 'touchmove' : 'mousemove',
6767
dragEnd: isMobile ? 'touchend' : 'mouseup'
68+
},
69+
70+
/**
71+
* get random order, using Fisher–Yates shuffle
72+
*/
73+
randomOrder: (length = this.options.music.length) => {
74+
function shuffle (arr) {
75+
for (let i = arr.length - 1; i >= 0; i--) {
76+
const randomIndex = Math.floor(Math.random() * (i + 1));
77+
const itemAtIndex = arr[randomIndex];
78+
arr[randomIndex] = arr[i];
79+
arr[i] = itemAtIndex;
80+
}
81+
return arr;
82+
}
83+
return shuffle([...Array(length)].map(function (item, i) {
84+
return i;
85+
}));
6886
}
6987
};
7088

0 commit comments

Comments
 (0)