Skip to content

Commit e1a6347

Browse files
committed
Refactor shuffle and update documentation
- Add early return for invalid sizes to shuffle - Rename variables to be more descriptive - Refactor moving list element, removing unnecessary operations - Unwrap if clause for adding to history because the condition is guaranteed by the guard clause - Inline the value 0 for the ReorderEvent - Update documentation to reflect new changes
1 parent bf8e879 commit e1a6347

1 file changed

Lines changed: 22 additions & 15 deletions

File tree

app/src/main/java/org/schabi/newpipe/player/playqueue/PlayQueue.java

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -422,34 +422,41 @@ public synchronized void unsetRecovery(final int index) {
422422
}
423423

424424
/**
425-
* Shuffles the current play queue.
425+
* Shuffles the current play queue
426426
* <p>
427-
* This method first backs up the existing play queue and item being played.
428-
* Then a newly shuffled play queue will be generated along with currently
429-
* playing item placed at the beginning of the queue.
427+
* This method first backs up the existing play queue and item being played. Then a newly
428+
* shuffled play queue will be generated along with currently playing item placed at the
429+
* beginning of the queue. This item will also be added to the history.
430430
* </p>
431431
* <p>
432-
* Will emit a {@link ReorderEvent} in any context.
432+
* Will emit a {@link ReorderEvent} if shuffled.
433433
* </p>
434+
*
435+
* @implNote Does nothing if the queue is empty or has a size of 1
434436
*/
435437
public synchronized void shuffle() {
438+
// Can't shuffle an list that's empty or only has one element
439+
if (size() <= 1) {
440+
return;
441+
}
442+
// Create a backup if it doesn't already exist
436443
if (backup == null) {
437444
backup = new ArrayList<>(streams);
438445
}
439-
final int originIndex = getIndex();
440-
final PlayQueueItem current = getItem();
446+
447+
final int originalIndex = getIndex();
448+
final PlayQueueItem currentItem = getItem();
449+
441450
Collections.shuffle(streams);
442451

443-
final int newIndex = streams.indexOf(current);
444-
if (newIndex != -1) {
445-
streams.add(0, streams.remove(newIndex));
446-
}
452+
// Move currentItem to the head of the queue
453+
streams.remove(currentItem);
454+
streams.add(0, currentItem);
447455
queueIndex.set(0);
448-
if (streams.size() > 0) {
449-
history.add(streams.get(0));
450-
}
451456

452-
broadcast(new ReorderEvent(originIndex, queueIndex.get()));
457+
history.add(currentItem);
458+
459+
broadcast(new ReorderEvent(originalIndex, 0));
453460
}
454461

455462
/**

0 commit comments

Comments
 (0)