Shuffled Cards

Randomizing a list of integers in JavaScript is tricky. First there is the trick to get a list of integers and then a trick to shuffle it. c2

# Application Frame

//frame.wiki.dbbs.co/assets/pages/snippet-template/esm.html HEIGHT 66

We need a function that displays the deck of cards in the Application Frame. We refer to this frame as a "deck-container".

// Function to emit HTML content for the deck container export async function emit(el) { el.innerHTML = ` <div id="deck-container"></div> <style>#deck-container {border: 1px solid black;}</style>`; } export async function bind(el) { console.log(el.innerHTML)

# linearShuffle

const deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']; console.log("Original deck:", deck);

const shuffle = linearShuffle(deck)

renderDeck(shuffle) console.log("Shuffled deck:", shuffle);

**Note**: Comment out the following code block to see the output of the deck of cards version in the Application Frame at the top of this page.

// Generate a random todo list with 10 items const randomTodoList = generateRandomTodoList(10); renderDeck(randomTodoList); console.log("Random todo list:", randomTodoList);

} // End of bind

# The Render Function

// Function to render the deck in the deck container async function renderDeck(deck) { // Parse the JSON string into an object // const deckObject = JSON.parse(deck); const deckObject = deck; // Select the deck container element const deckContainer = document.getElementById('deck-container'); // Render the deck in the deck container deckContainer.innerHTML = `<pre>${JSON.stringify(deckObject)}</pre>`; }

# The linearShuffle Function

function linearShuffle(deck) { for (let i = deck.length - 1; i > 0; i--) { // Generate a random index between 0 and i (inclusive) const j = Math.floor(Math.random() * (i + 1)); // Swap deck[i] with deck[j] [deck[i], deck[j]] = [deck[j], deck[i]]; } return deck; }

Is this an example of Destructuring Assignment, a feature introduced in ES6 (ECMAScript 2015)? mdn ecma

How could we apply this to our Random Walk in the Speed Bot Journey?

We want to a watch a random todo list.

We could:

1. Create an array of integers representing the todo list items.

2. Shuffle the array to randomize the order of items.

# generateRandomTodoList

Here's a function that could accomplish this:

function generateRandomTodoList(numItems) { // Create an array of integers from 1 to numItems const todoList = Array.from({ length: numItems }, (_, index) => index + 1); // Shuffle the array for (let i = todoList.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [todoList[i], todoList[j]] = [todoList[j], todoList[i]]; } return todoList; }