Skip to content

draw

從數組中隨機抽取一個元素。

語法

typescript
draw<T>(
  array: T[]
): T | undefined

參數

  • array (T[]): 要抽取的數組

返回值

  • T | undefined: 隨機抽取的元素,如果數組為空則返回 undefined

示例

基本用法

typescript
import { draw } from 'radash'

const fruits = ['apple', 'banana', 'cherry', 'date']
const randomFruit = draw(fruits)
// 可能返回: 'apple', 'banana', 'cherry', 或 'date'

處理空數組

typescript
import { draw } from 'radash'

const emptyArray: string[] = []
const result = draw(emptyArray)
// undefined

處理單個元素數組

typescript
import { draw } from 'radash'

const singleElement = ['hello']
const result = draw(singleElement)
// 'hello'

處理數字數組

typescript
import { draw } from 'radash'

const numbers = [1, 2, 3, 4, 5, 6]
const randomNumber = draw(numbers)
// 可能返回: 1, 2, 3, 4, 5, 或 6

處理對象數組

typescript
import { draw } from 'radash'

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

const randomUser = draw(users)
// 可能返回: { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, 或 { id: 3, name: 'Charlie' }

處理混合類型數組

typescript
import { draw } from 'radash'

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

游戲應用

typescript
import { draw } 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♣'
  ]

  drawCard(): string | undefined {
    return draw(this.deck)
  }
}

const game = new CardGame()
const card = game.drawCard()
// 可能返回: 'A♠', '2♥', 'K♦', 等

隨機選擇器

typescript
import { draw } from 'radash'

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

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

  select(): T | undefined {
    return draw(this.items)
  }

  selectMultiple(count: number): T[] {
    const result: T[] = []
    for (let i = 0; i < count && this.items.length > 0; i++) {
      const item = draw(this.items)
      if (item !== undefined) {
        result.push(item)
        // 從數組中移除已選擇的項目
        const index = this.items.indexOf(item)
        if (index > -1) {
          this.items.splice(index, 1)
        }
      }
    }
    return result
  }
}

const selector = new RandomSelector(['red', 'green', 'blue', 'yellow'])
const color = selector.select()
// 可能返回: 'red', 'green', 'blue', 或 'yellow'

隨機任務分配

typescript
import { draw } 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 assignRandomTask(): Task | undefined {
  return draw(tasks)
}

const assignedTask = assignRandomTask()
// 可能返回任意一個任務

隨機顏色生成

typescript
import { draw } from 'radash'

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

function getRandomColor(): string | undefined {
  return draw(colors)
}

const color = getRandomColor()
// 可能返回任意一個顏色值

隨機問候語

typescript
import { draw } from 'radash'

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

function getRandomGreeting(): string | undefined {
  return draw(greetings)
}

const greeting = getRandomGreeting()
// 可能返回任意一個問候語

隨機笑話

typescript
import { draw } 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 | undefined {
  return draw(jokes)
}

const joke = getRandomJoke()
// 可能返回任意一個笑話

隨機密碼生成

typescript
import { draw } from 'radash'

const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
const numbers = '0123456789'
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?'

function generatePassword(length: number): string {
  const allChars = letters + numbers + symbols
  let password = ''
  
  for (let i = 0; i < length; i++) {
    const char = draw(allChars.split(''))
    if (char !== undefined) {
      password += char
    }
  }
  
  return password
}

const password = generatePassword(8)
// 生成8位隨機密碼

注意事項

  1. 隨機性: 每次調用都可能返回不同的結果
  2. 空數組: 如果數組為空,返回 undefined
  3. 不修改原數組: 不會修改原始數組
  4. 類型安全: 支持完整的 TypeScript 類型推斷

與其他函數的區別

  • draw: 隨機抽取一個元素
  • shuffle: 隨機打亂數組順序
  • random: 生成隨機數字
  • sample: 隨機抽取多個元素

性能

  • 時間復雜度: O(1)
  • 空間復雜度: O(1)
  • 適用場景: 隨機選擇、游戲邏輯、隨機化

Released under the MIT License.