utils.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import Diacritics from "diacritic";
  2. /**
  3. * Check if element or parent has className.
  4. * @param {DOMElement} element
  5. * @param {string} className
  6. */
  7. export const hasClass = (element, className) =>
  8. typeof element.className === "string" &&
  9. element.className.split(" ").includes(className);
  10. export const insideClass = (element, className) => {
  11. if (hasClass(element, className)) {
  12. return element;
  13. }
  14. if (!element.parentNode) {
  15. return false;
  16. }
  17. return insideClass(element.parentNode, className);
  18. };
  19. export const isPointInsideRect = (point, rect) => {
  20. return (
  21. point.x > rect.left &&
  22. point.x < rect.left + rect.width &&
  23. point.y > rect.top &&
  24. point.y < rect.top + rect.height
  25. );
  26. };
  27. export const isItemInsideElement = (itemElement, otherElem) => {
  28. const rect = otherElem.getBoundingClientRect();
  29. const fourElem = Array.from(itemElement.querySelectorAll(".corner"));
  30. return fourElem.every((corner) => {
  31. const { top: y, left: x } = corner.getBoundingClientRect();
  32. return isPointInsideRect({ x, y }, rect);
  33. });
  34. };
  35. /**
  36. * Shuffles array in place.
  37. * @param {Array} a items An array containing the items.
  38. */
  39. export const shuffle = (a) => {
  40. for (let i = a.length - 1; i > 0; i--) {
  41. const j = Math.floor(Math.random() * (i + 1));
  42. [a[i], a[j]] = [a[j], a[i]];
  43. }
  44. return a;
  45. };
  46. export const randInt = (min, max) => {
  47. return Math.floor(Math.random() * (max - min + 1)) + min;
  48. };
  49. const cleanWord = (word) => {
  50. return Diacritics.clean(word).toLowerCase();
  51. };
  52. export const search = (term, string) => {
  53. let strings = string;
  54. if (typeof string === "string") {
  55. strings = [string];
  56. }
  57. const cleanedTerm = cleanWord(term);
  58. return strings.some((s) => cleanWord(s).includes(cleanedTerm));
  59. };