utils.js 1.6 KB

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