JSFiddle - React, Tailwind, and code Playground

by jarosciak

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bananagrams Solver</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Bananagrams Solver</h1>
  <input id="input-field" type="text" placeholder="Enter tiles (e.g. BANANA)">
  <button id="solve-button">Solve</button>
  <textarea id="output-field" rows="10" cols="40"></textarea>

  <script src="bananagrams-solver.js"></script>
</body>
</html>

CSS

body {
  font-family: Arial, sans-serif;
  text-align: center;
}

input[type="text"] {
  width: 50%;
  padding: 10px;
  font-size: 18px;
}

button[type="button"] {
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
}

textarea {
  width: 50%;
  padding: 10px;
  font-size: 18px;
  resize: vertical;
}

JavaScript

const dictionaryApi = 'https://api.datamuse.com/words';
const tileCount = {
  'A': 13, 'B': 3, 'C': 3, 'D': 6, 'E': 18, 'F': 3, 'G': 4, 'H': 5, 'I': 12, 'J': 2, 'K': 2, 'L': 5, 'M': 3, 'N': 8, 'O': 15, 'P': 4, 'Q': 2, 'R': 9, 'S': 10, 'T': 12, 'U': 4, 'V': 3, 'W': 3, 'X': 2, 'Y': 3, 'Z': 2
};

function loadDictionary() {
  return fetch(dictionaryApi)
   .then(response => response.json())
   .then(data => data.map(word => word.word));
}

function getTileCount(tile) {
  return tileCount[tile.toUpperCase()];
}

function generateAnagrams(tiles) {
  const anagrams = [];
  for (let i = 0; i < tiles.length; i++) {
    for (let j = i + 1; j <= tiles.length; j++) {
      const subset = tiles.slice(i, j);
      const sortedSubset = subset.split('').sort().join('');
      anagrams.push(sortedSubset);
    }
  }
  return anagrams;
}

function filterValidWords(anagrams, dictionary) {
  return anagrams.filter(anagram => dictionary.includes(anagram));
}

function solveBananagrams(tiles) {
  return loadDictionary()
   .then(dictionary => {
      const anagrams = generateAnagrams(tiles);
      const validWords = filterValidWords(anagrams, dictionary);
      return validWords;
    });
}

document.addEventListener('DOMContentLoaded', () => {
  const inputField = document.getElementById('input-field');
  const solveButton = document.getElementById('solve-button');
  const outputField = document.getElementById('output-field');

  solveButton.addEventListener('click', () => {
    const tiles = inputField.value.toUpperCase();
    solveBananagrams(tiles)
     .then(validWords => {
        outputField.value = validWords.join('\n');
      })
     .catch(error => console.error(error));
  });
});