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.
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.
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); }
This function is responsible for checking whether a given word exists in the Wordnik API by querying its Scrabble score endpoint.
URL setup:
API request:
This is the main function that unscrambles the input word and validates each permutation.
Get input:
Generate permutations:
Validate each word:
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!