-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/** | ||
* 打乱一个数组。 | ||
* | ||
* @param arr 要打乱的数组 | ||
* @returns 打乱后的数组 | ||
* @see https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/ | ||
*/ | ||
export default function shuffle<T>(arr: T[]): T[] { | ||
if (!Array.isArray(arr)) { | ||
return arr | ||
} | ||
const newArr = arr.slice() | ||
for (let i = newArr.length - 1; i >= 0; i--) { | ||
const randomIndex = Math.floor(Math.random() * (i + 1)) | ||
const itemAtIndex = newArr[randomIndex] | ||
newArr[randomIndex] = newArr[i] | ||
newArr[i] = itemAtIndex | ||
} | ||
return newArr | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters