Home > Web Front-end > JS Tutorial > Building a Word Unscrambler with JavaScript (part 4)

Building a Word Unscrambler with JavaScript (part 4)

Mary-Kate Olsen
Release: 2024-10-16 18:26:02
Original
902 people have browsed it

Hey everyone! ?

Last time, I went on a mini-adventure searching for the best API, and after testing out several options, I settled on Wordnik. It has a massive word database, and though it took a week to get the API keys, I finally got them. Now it’s time to integrate it and check if the words generated from our permutations are actually valid.

The Challenge: Validating Words

One thing I realized is that most dictionary APIs, including Wordnik, don’t have a direct way to check if a word exists. They provide definitions and examples but not straightforward validation.
To work around this, I used Wordnik’s Scrabble score endpoint. The logic is simple: if a word has a Scrabble score, it’s considered valid.

Here's the code to implement this validation:

async function isValidWord(word) {
    const apiKey = 'API_KEY'; // use your own API keys
    const url = `https://api.wordnik.com/v4/word.json/${word}/scrabbleScore?api_key=${apiKey}`;

    try {
        const response = await fetch(url);

        if (response.status === 200) {
            return true;  // Word is valid
        } else if (response.status === 404) {
            return false; // Word not found in dictionary
        } else {
            console.error(`Error: Received status ${response.status} for word "${word}"`);
            return false; 
        }
    } catch (error) {
        console.error('Error checking word validity:', error);
        return false;
    }
}

async function descrambleWords() {
    const input = document.getElementById('scrambledInput').value;
    const combinations = generatePermutations(input); 
    const validWords = [];

    // Check each word one by one for validity
    for (const word of combinations) {
        const isValid = await isValidWord(word);
        if (isValid) {
            validWords.push(word); // Only push valid words
        }
    }

    const categorizedWords = categorizeByLength(validWords); 
    displayResults(categorizedWords); 
}
Copy after login

Breaking It Down

async function isValidWord(word)

This function is responsible for checking whether a given word exists in the Wordnik API by querying its Scrabble score endpoint.

  1. URL setup:

    • The function constructs an API request using the word we want to check and appends it to the base URL for the Scrabble score endpoint.
    • Example: For the word "apple", the URL would be: https://api.wordnik.com/v4/word.json/apple/scrabbleScore?api_key=YOUR_API_KEY.
  2. API request:

    • await fetch(url) sends an HTTP request to the Wordnik API.
    • Response handling:
      • 200 (OK): If the API returns a 200 status, it means the word exists and has a Scrabble score. We treat this as a valid word and return true.
      • 404 (Not Found): If the API returns a 404, the word is not found in the dictionary, and we return false.
      • Any other status code is logged as an error, and we return false to indicate the word is invalid or there was an issue.

async function descrambleWords()

This is the main function that unscrambles the input word and validates each permutation.

  1. Get input:

    • It first grabs the scrambled word from the input field using document.getElementById('scrambledInput').value.
  2. Generate permutations:

    • The function calls generatePermutations(input) to generate all possible combinations of the scrambled word.
  3. Validate each word:

    • It then loops through each permutation and calls isValidWord(word) to check if it's valid.
    • If the word is valid (i.e., it exists in the Wordnik API), it gets added to the validWords array.

Building a Word Unscrambler with JavaScript (part 4)
I will share the live link as soon as I find a way to secure my API keys before pushing to GitHub.

Another hurdle was the rate limit imposed by Wordnik’s API. When I exceeded the limit, the validation process hit a 429 (Too Many Requests) error, halting everything. A potential solution I’m considering is adding a delay when the limit is reached to avoid overloading the API.

If you have any better ideas or suggestions, feel free to share in the comments or reach out to me on Twitter.

Next up: I’ll be working on optimizing performance, find a solution to the rate limit and ensuring the input only accepts strings, no numbers.
Stay tuned for more updates!

The above is the detailed content of Building a Word Unscrambler with JavaScript (part 4). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template