Leveraging an array with a switch() function in JavaScript

I am currently working on creating a simplified poker game using JavaScript. I have documented all potential card combinations that a player may have in their hand, organized by their value. Here's an example:

switch(sortedHand)
{           
 //Pair
     case [1,1,4,3,2]: sortedHand.push(1,"Pair"); break;
     case [1,1,5,3,2]: sortedHand.push(2,"Pair"); break; 
     case [1,1,5,4,2]: sortedHand.push(3,"Pair"); break;
     case [1,1,5,4,3]: sortedHand.push(4,"Pair"); break;
     case [1,1,6,3,2]: sortedHand.push(5,"Pair"); break;
     case [1,1,6,4,2]: sortedHand.push(6,"Pair"); break;
     case [1,1,6,4,3]: sortedHand.push(7,"Pair"); break;
     case [1,1,6,5,2]: sortedHand.push(8,"Pair"); break;
     case [1,1,6,5,3]: sortedHand.push(9,"Pair"); break;
     case [1,1,6,5,4]: sortedHand.push(10,"Pair"); break;

Although the "sortedHand" array is successfully storing values (confirmed through console.log), the switch() statement consistently defaults to the default case, resulting in everyone having a straight flush. It seems like my approach of defining exact array values for comparison with "sortedHand" might be causing this issue, but I'm not sure what the correct approach should be. Is it feasible to utilize switch() in this manner?

Answer №1

One approach is to use a switch statement based on the textual representation of the array.

switch(sortedHand.join(' '))
{           
    //Pair
    case '1 1 4 3 2': sortedHand.push(1,"Pair"); break;
    case '1 1 5 3 2': sortedHand.push(2,"Pair"); break; 
    case '1 1 5 4 2': sortedHand.push(3,"Pair"); break;
    case '1 1 5 4 3': sortedHand.push(4,"Pair"); break;
    // etc.
}

Another option is to create a function dispatch table using an object instead of directly specifying each case in the switch statement.

var dispatch = {};

// Customize the table based on your needs
for (var i = 0; i < 10; i++) {
    (function(i) {
        var hand = ...; // Add custom logic for hands here
        dispatch[hand] = function() { sortedHand.push(i, "Pair"); };
    })(i);
}

// Execute the appropriate function
dispatch[sortedHand.join(' ')]();

Answer №2

It is a common misconception that the switch() statement always returns the default case.

This is due to the fact that the comparison within the switch statement does not check the array contents, but rather the array object itself. Objects are considered equal by their identity, so an object instantiated by a literal will not be equal to anything else.

Can switch() actually be used in this way?

Yes, it is possible to use objects in switch statements, but references would need to be used in the cases for it to work effectively - which is not applicable to your current problem.

In this scenario, my suggestion would be to stringify:

switch(sortedHand.join())
{           
 //Pair
     case "1,1,4,3,2": sortedHand.push(1,"Pair"); break;
     case "1,1,5,3,2": sortedHand.push(2,"Pair"); break; 
     case "1,1,5,4,2": sortedHand.push(3,"Pair"); break;
     case "1,1,5,4,3": sortedHand.push(4,"Pair"); break;
     case "1,1,6,3,2": sortedHand.push(5,"Pair"); break;
     case "1,1,6,4,2": sortedHand.push(6,"Pair"); break;
     case "1,1,6,4,3": sortedHand.push(7,"Pair"); break;
     case "1,1,6,5,2": sortedHand.push(8,"Pair"); break;
     case "1,1,6,5,3": sortedHand.push(9,"Pair"); break;
     case "1,1,6,5,4": sortedHand.push(10,"Pair"); break;

However, there may be a more efficient arithmetic solution to detect the patterns you are looking for. This could potentially make your code shorter and faster, though without knowing the exact purpose of this snippet, it's hard to provide specific advice.

Answer №3

For a more efficient and adaptable approach, consider utilizing objects instead of switch cases:

var options = {
    '1 1 4 3 2': 1,
    '1 1 5 3 2': 2,
    '1 1 5 4 2': 3,
    '1 1 5 4 3': 4
}[sortedHand.join(' ')];

if (options) { 
    sortedHand.push(options, "Pair"); 
}

Objects are particularly effective when there is a direct mapping between input and output values. If your logic involves multiple actions for each case, using switch cases may be necessary. However, for simple one-to-one transformations like X becoming Y, Objects in the form of Look Up Tables work perfectly.

A regular expression could potentially be utilized here as well. I have previously employed them in a connect4 game to identify four in a row. Nevertheless, the aforementioned logical table should offer a comparable or superior solution to what you have described.

Answer №4

While the suggestion you provided may not work perfectly, one alternative is to utilize sortedHand.join(',') and compare it with [1,1,1,2,5].join(','). This method will check if the two arrays have the same content and should return true in such a case (Remember to be cautious when dealing with numbers as strings!) However, it's worth noting that this approach might not be ideal for designing your logic. Even a basic card game can yield numerous possible hands. It would be more efficient to leverage the collection management functions offered by underscore.js, as it simplifies the process and promotes better coding practices.

Answer №5

Exploring the vast realm of 1274 potential combinations from a standard deck of cards can be overwhelming. Instead of exhaustively listing them in a switch statement, consider utilizing a function to detect any duplicates and identify patterns like pairs, three-of-a-kinds, four-of-a-kinds, and straights. (Note: Suit information may not be necessary for this task.)

For those determined to pursue the switch statement route, keep in mind that strings also work well with switches and can mimic array-like behavior. For instance, "123"[0] will return '1'. To convert between string and integer representations, functions like parseInt can be quite handy.

Answer №6

In case this solution hasn't been proposed yet, you can implement a for loop to tally the number of cards with the exact specified value. By creating this function, you will be able to use 'cardCount = count(sortedHand, cardNumber)' whenever needed. Simply iterating through all possible card numbers will reveal the hands.

Considering that a player can only hold combinations like 1 pair, 2 pairs, 3 of a kind, full house (3 of a kind + 1 pair), 4 of a kind, or straights, you can iterate and return an array containing all the matches as arrays/objects indicating the frequency and the card number associated. For example, [{2, 5}, {3, 6}] would represent a full house.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

Issue with MERN stack: User not being saved in mongoDB despite lack of errors

Check out the repository at https://github.com/QexleLLC/Otlic After running the frontend with npm start, and starting the backend with nodemon server, everything appeared to be working fine. However, when I tried signing up by going to localhost:3000/sign ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Start playback of a video with Jquery (HTML5 video tag)

In order to track the last time a video stops playing and resume from that point later, I am using the html5 video element's duration property. This information is then sent to the database for storage. Here is an example of how this can be achieved: ...

"Enhance Your Searching Experience with Top-Tier AngularJS

Presented below is a dataset: persons = [ { "age":20, "parameter1":94, "name":"Foobarin" }, { "age":33, "parameter1":49, "name":"Johan" } ] I am looking to develop a sophisticated live search functionality that can identify specific ...

Most effective method to change a specific attribute in every element within a nested array of objects

Below is an example of my data object structure: const courses = [ { degree: 'bsc', text: 'Some text', id: 'D001', }, { degree: 'beng', text: 'Some text&apos ...

Retrieving two values from a 2-dimensional array but displaying only one

Hey there, I'm trying to extract the first word from an array I've created and then display its antonym upon clicking a "flip" button. Basically, I want to fetch the 0th and 1st elements but only reveal the 0th one initially until the user clicks ...

React: Updating useState array by removing the first element triggered by an event or timer

I am currently working on a function that populates a useState array containing objects representing cars. These cars appear on the left side of the screen and move across until they are off-screen. My goal is to remove these cars from the state array once ...

An issue in ASP.net user control not triggering a specific javascript function

I am currently working on an asp.net web application where I have implemented a repeater that calls a registered user control. Within this user control, there is a button that is supposed to trigger a Javascript function to make an Ajax call for server-sid ...

What is the best way to transform a database object into a complex JSON structure?

My goal is to retrieve a specific person from a list of persons. The POST method works correctly and I am able to obtain the desired person as "chosenPerson" in the controller. However, when I try to convert this person into a complex JSON object using ser ...

Is there a vanilla JavaScript alternative to using jQuery's document on click event for handling link clicks?

Does a standalone JavaScript version of this exist? document.addEventListener('click', function(event) { event.preventDefault(); here.change(this); }); I am specifically interested in adding event listeners to any dynamically created links, ...

What is the process of declaring state in React components?

I have recently started learning React and I am curious about how this code snippet should function: class App extends Component { > 4 | state = { | ^ 5 | bands: [], 6 | concerts: [] 7 | } Below is the error message being ...

Merge the arrays from various objects stored in a MongoDB database

As I delve into exploring mongodb, my goal is to combine the images into a single array. For example: {user_id:01, images:[10,20,30,40,50]} {user_id:02, images:[11,22,33,44,55]} {user_id:03, images:[12,22,32,42,52]} {user_id:04, images:[13,23,33,43,53]} ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

The npm package for google-spreadsheet.js is experiencing issues and is not functioning correctly when trying to replicate the GitHub

After attempting to implement the basic example code provided at https://github.com/theoephraim/node-google-spreadsheet, I encountered an issue. For instance: const { GoogleSpreadsheet } = require('google-spreadsheet') const creds = require(&apo ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

Is there a way to effortlessly zoom in on a Google map with just one mouse click?

Can the Google Maps be zoomed to a specific level with just one click of the mouse? ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...