All files / libs/algorithms/src shuffle.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 1/1
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171x 1x 1x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 6x 2x 2x  
import { random } from "./random";
// Fisher–Yates algorithm
export const shuffle = <Element>(array: Element[]): Element[] => {
    const sorted = array.slice();
    let currentIndex: number = array.length;
    let randomIndex: number;
    // While there remain elements to shuffle...
    while (currentIndex !== 0) {
        // Pick a remaining element...
        randomIndex = random(0, currentIndex);
        currentIndex -= 1;
        // And swap it with the current element.
        [sorted[currentIndex], sorted[randomIndex]] = [sorted[randomIndex], sorted[currentIndex]];
    }
    return sorted;
};