How to create a flexible object?

How do I create an dictionary object of words?

  • I am using Javascript to make a simple text game. This is a Japanese game called shiritori. You take the last character of a word and think of a word that starts with that character. Word1: とり Word2: りんご As you can see the last charactor of Word1 is the first character of Word2. The problem I am having is with create a dictionary object to check if the word is valid or not. After a word is played, I want to check 1. The word exists in the dictionary 2. Has not been played 3. The meaning of the word so I can print that into a div My attempt was something like this checks within the dictionary where the key is equal to the last character var dictionary = {ã‚Š:""} Under the last character are all the words in the dictionary that starts with that character var dictionary = {ã‚Š:{"りんご":"", "りす": ""}}; Within the word, it contains value if it has been played and the meaning. var dictionary = {ã‚Š:{"りんご": {played: false, meaning: "apple"}, "りす": {played: false, meaning: "squirrel"}}}; As you might see, this did not work. How could I make what I'm trying to do?

  • Answer:

    Cool stuff, I love しりとり :D You might want to consider breaking up what you're trying to do into two parts.  Keep the state of the game (the words that have been played) in one data structure and the dictionary in another.  This prevents you from having a lot of JS objects with { played: false }, and gives you a better logical separation of the game and the dictionary. Push the words that have been played instead into an array.  This also helps later, since you can see the final chain of words that was created during the entire game.  When you want to make sure that a word hasn't been played before, then you can just do an indexOf check inside that array. For how the dictionary should be organized, you had a good starting point.  Now that you don't need to worry about whether a word was played or not, you can simplify it to: var dictionary = { "ã‚Š": { "りんご" : "apple", "りす" : "squirrel" } }; Then, you can just use an in statement to check whether a word is in there or not: "りんご" in dictionary["ã‚Š"]; // > true "りか" in dictionary["ã‚Š"] // > false Hope this helps, would love to see the final game!

Clarence Leung at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.