mShuffle

mShuffle

  • (anArray: array) => anArray
  1. Randomly order an array

    Consider shuffle instead.
    This is for the uncommon case where mutating anArray is required.

    const arr = [1, 2, 3]
    const mutatedArr = mShuffle(arr)
    
    console.log(mutatedArr === arr) // is true
    console.log(arr) // is a random order of  1, 2, 3
    const arr = [1, 2, 3]
    const mutatedArr = mShuffle(arr)
    
    console.log(mutatedArr === arr) // is true
    console.log(arr) // is a random order of  1, 2, 3
    
    const arr = [1, 2, 3]
    const mutatedArr = mShuffle(arr)
    
    console.log(mutatedArr === arr) // is true
    console.log(arr) // is a random order of  1, 2, 3
    const arr = [1, 2, 3]
    const mutatedArr = mShuffle(arr)
    
    console.log(mutatedArr === arr) // is true
    console.log(arr) // is a random order of  1, 2, 3
    
  2. Sometimes we want to mutate an array by ordering it randomly. Below, we have groups of cards for a quick version of Clue. Let's shuffle each group to start the game.

    const cards = {
      rooms: ['ballroom', 'conservatory', 'lounge'],
      suspects: ['Colonel Mustard', 'Miss Scarlet', 'Professor Plum'],
      weapons: ['dagger', 'rope', 'wrench'],
    }
    
    const shuffleEachGroup = forEach(mShuffle)
    shuffleEachGroup(cards)
    
    console.log(cards)
    // each group of cards will be randomly ordered
    type Cards = Record<string, string[]>
    const cards: Cards = {
      rooms: ['ballroom', 'conservatory', 'lounge'],
      suspects: ['Colonel Mustard', 'Miss Scarlet', 'Professor Plum'],
      weapons: ['dagger', 'rope', 'wrench'],
    }
    
    const shuffleEachGroup = forEach(mShuffle<string[]>)<Cards>
    shuffleEachGroup(cards)
    
    console.log(cards)
    // each group of cards will be randomly ordered
    
    const cards = {
      rooms: ['ballroom', 'conservatory', 'lounge'],
      suspects: [
        'Colonel Mustard',
        'Miss Scarlet',
        'Professor Plum',
      ],
      weapons: ['dagger', 'rope', 'wrench'],
    }
    
    const shuffleEachGroup = forEach(mShuffle)
    shuffleEachGroup(cards)
    
    console.log(cards)
    // each group of cards will be randomly ordered
    type Cards = Record<string, string[]>
    const cards: Cards = {
      rooms: ['ballroom', 'conservatory', 'lounge'],
      suspects: [
        'Colonel Mustard',
        'Miss Scarlet',
        'Professor Plum',
      ],
      weapons: ['dagger', 'rope', 'wrench'],
    }
    
    const shuffleEachGroup = forEach(
      mShuffle<string[]>
    )<Cards>
    shuffleEachGroup(cards)
    
    console.log(cards)
    // each group of cards will be randomly ordered