nearest.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const getSprite = pokemon => `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`
  2. const onColorChange = () => {
  3. const numPoke = document.getElementById("num-poke")?.value;
  4. document.getElementById("num-poke-display").innerHTML = numPoke;
  5. const closeCoeff = document.getElementById("close-coeff")?.value;
  6. document.getElementById("close-coeff-display").innerHTML = closeCoeff;
  7. const bestList = document.getElementById("best-list");
  8. bestList.innerHTML = ''; // do the lazy thing
  9. const color = document.getElementById("color-input")?.value;
  10. if (color.length !== 6) {
  11. return;
  12. }
  13. document.querySelector("body").setAttribute("style", `background: #${color}`);
  14. const colorValues = [
  15. Number.parseInt(color.substring(0, 2), 16),
  16. Number.parseInt(color.substring(2, 4), 16),
  17. Number.parseInt(color.substring(4, 6), 16),
  18. ];
  19. database.map(([name, x, ...y]) => ({
  20. name,
  21. score: x - closeCoeff * y.map((yc, i) => yc * colorValues[i]).reduce((x, y) => x + y),
  22. }))
  23. .sort((a, b) => a.score - b.score)
  24. .map(({ name }) => name)
  25. .slice(0, numPoke)
  26. .forEach(name => {
  27. const li = document.createElement("li");
  28. const img = document.createElement("img");
  29. img.setAttribute("src", getSprite(name));
  30. li.appendChild(img)
  31. li.appendChild(document.createTextNode(name));
  32. bestList.appendChild(li);
  33. });
  34. };
  35. const onRandomColor = () => {
  36. const colorInput = document.getElementById("color-input");
  37. colorInput.value = hsvToRGB(Math.random(), 0.9, 0.9);
  38. onColorChange();
  39. };
  40. // mostly stolen from https://stackoverflow.com/a/17243070
  41. // adapted slightly
  42. const hsvToRGB = (h, s, v) => {
  43. var r, g, b, i, f, p, q, t;
  44. i = Math.floor(h * 6);
  45. f = h * 6 - i;
  46. p = v * (1 - s);
  47. q = v * (1 - f * s);
  48. t = v * (1 - (1 - f) * s);
  49. switch (i % 6) {
  50. case 0: r = v, g = t, b = p; break;
  51. case 1: r = q, g = v, b = p; break;
  52. case 2: r = p, g = v, b = t; break;
  53. case 3: r = p, g = q, b = v; break;
  54. case 4: r = t, g = p, b = v; break;
  55. case 5: r = v, g = p, b = q; break;
  56. }
  57. return [r, g, b].map(c => Math.round(c * 255).toString(16).padStart(2, "0")).reduce((x, y) => x + y);
  58. }