Skip to content

shuffle

随机打乱数组元素的顺序。

语法

typescript
shuffle<T>(array: T[]): T[]

参数

  • array (T[]): 要打乱的数组

返回值

  • T[]: 打乱顺序后的新数组

示例

基本用法

typescript
import { shuffle } from 'radash'

const numbers = [1, 2, 3, 4, 5]
const shuffled = shuffle(numbers)
// 可能返回: [3, 1, 5, 2, 4]

处理字符串数组

typescript
import { shuffle } from 'radash'

const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
const shuffledFruits = shuffle(fruits)
// 可能返回: ['cherry', 'apple', 'elderberry', 'banana', 'date']

处理对象数组

typescript
import { shuffle } from 'radash'

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'Diana' }
]

const shuffledUsers = shuffle(users)
// 可能返回: [
//   { id: 3, name: 'Charlie' },
//   { id: 1, name: 'Alice' },
//   { id: 4, name: 'Diana' },
//   { id: 2, name: 'Bob' }
// ]

处理空数组

typescript
import { shuffle } from 'radash'

const emptyArray: number[] = []
const shuffled = shuffle(emptyArray)
// []

处理单个元素数组

typescript
import { shuffle } from 'radash'

const singleElement = ['hello']
const shuffled = shuffle(singleElement)
// ['hello'] (顺序不变)

处理混合类型数组

typescript
import { shuffle } from 'radash'

const mixed = ['hello', 42, true, { key: 'value' }]
const shuffled = shuffle(mixed)
// 可能返回: [42, { key: 'value' }, 'hello', true]

游戏应用

typescript
import { shuffle } from 'radash'

class CardGame {
  private deck = [
    'A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠',
    'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥',
    'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦',
    'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣'
  ]

  shuffleDeck() {
    this.deck = shuffle(this.deck)
  }

  dealCards(count: number) {
    return this.deck.slice(0, count)
  }
}

const game = new CardGame()
game.shuffleDeck()
const hand = game.dealCards(5)
// 返回5张随机牌

随机选择器

typescript
import { shuffle } from 'radash'

class RandomSelector<T> {
  private items: T[]

  constructor(items: T[]) {
    this.items = [...items]
  }

  shuffle() {
    this.items = shuffle(this.items)
  }

  select(count: number): T[] {
    return this.items.slice(0, count)
  }

  selectAll(): T[] {
    return shuffle(this.items)
  }
}

const selector = new RandomSelector(['red', 'green', 'blue', 'yellow', 'purple'])
const colors = selector.select(3)
// 返回3个随机颜色

随机任务分配

typescript
import { shuffle } from 'radash'

interface Task {
  id: number
  name: string
  priority: 'low' | 'medium' | 'high'
}

const tasks: Task[] = [
  { id: 1, name: 'Write documentation', priority: 'high' },
  { id: 2, name: 'Fix bug', priority: 'high' },
  { id: 3, name: 'Add tests', priority: 'medium' },
  { id: 4, name: 'Refactor code', priority: 'medium' },
  { id: 5, name: 'Update dependencies', priority: 'low' }
]

function assignRandomTasks(taskCount: number): Task[] {
  const shuffledTasks = shuffle(tasks)
  return shuffledTasks.slice(0, taskCount)
}

const assignedTasks = assignRandomTasks(3)
// 返回3个随机任务

随机颜色生成

typescript
import { shuffle } from 'radash'

const colors = [
  '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
  '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
]

function getRandomColors(count: number): string[] {
  return shuffle(colors).slice(0, count)
}

const randomColors = getRandomColors(5)
// 返回5个随机颜色

随机问候语

typescript
import { shuffle } from 'radash'

const greetings = [
  'Hello!',
  'Hi there!',
  'Good morning!',
  'Good afternoon!',
  'Good evening!',
  'Hey!',
  'Greetings!',
  'Welcome!'
]

function getRandomGreeting(): string {
  return shuffle(greetings)[0]
}

const greeting = getRandomGreeting()
// 返回一个随机问候语

随机笑话

typescript
import { shuffle } from 'radash'

const jokes = [
  'Why don\'t scientists trust atoms? Because they make up everything!',
  'Why did the scarecrow win an award? Because he was outstanding in his field!',
  'Why don\'t eggs tell jokes? They\'d crack each other up!',
  'What do you call a fake noodle? An impasta!',
  'Why did the math book look so sad? Because it had too many problems!'
]

function getRandomJoke(): string {
  return shuffle(jokes)[0]
}

const joke = getRandomJoke()
// 返回一个随机笑话

随机密码生成

typescript
import { shuffle } from 'radash'

function generatePassword(length: number): string {
  const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const numbers = '0123456789'
  const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?'
  
  const allChars = letters + numbers + symbols
  const shuffledChars = shuffle(allChars.split(''))
  
  return shuffledChars.slice(0, length).join('')
}

const password = generatePassword(8)
// 生成8位随机密码

随机测试数据

typescript
import { shuffle } from 'radash'

const testData = [
  { id: 1, value: 'test1' },
  { id: 2, value: 'test2' },
  { id: 3, value: 'test3' },
  { id: 4, value: 'test4' },
  { id: 5, value: 'test5' }
]

function getRandomTestData(count: number) {
  return shuffle(testData).slice(0, count)
}

const randomData = getRandomTestData(3)
// 返回3个随机测试数据

随机排序

typescript
import { shuffle } from 'radash'

const students = [
  { name: 'Alice', grade: 85 },
  { name: 'Bob', grade: 92 },
  { name: 'Charlie', grade: 78 },
  { name: 'Diana', grade: 95 },
  { name: 'Eve', grade: 88 }
]

function randomizePresentationOrder() {
  return shuffle(students)
}

const presentationOrder = randomizePresentationOrder()
// 返回随机排序的学生列表

注意事项

  1. 不可变性: 不会修改原数组
  2. 随机性: 每次调用都可能返回不同的结果
  3. 性能: 使用 Fisher-Yates 洗牌算法
  4. 类型安全: 支持完整的 TypeScript 类型推断

与其他函数的区别

  • shuffle: 随机打乱数组顺序
  • draw: 随机抽取一个元素
  • random: 生成随机数字
  • sample: 随机抽取多个元素

性能

  • 时间复杂度: O(n),其中 n 是数组长度
  • 空间复杂度: O(n)
  • 适用场景: 游戏、随机化、测试数据生成

Released under the MIT License.