array.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { matcher } from './matcher.js';
  2. /**
  3. * Split an array based on size
  4. * @param arr
  5. * @param chunkSize
  6. * @returns
  7. */
  8. export const toChunks = (arr, chunkSize) => {
  9. return arr.reduce((prev, _, i) => i % chunkSize ? prev : [...prev, arr.slice(i, i + chunkSize)], []);
  10. };
  11. /**
  12. * simple method to normalize any string to array
  13. * @param inp
  14. */
  15. export const toArray = (inp) => {
  16. return typeof inp === 'string' ? [inp] : inp;
  17. };
  18. /**
  19. * Returns the difference between two arrays
  20. * @param inputArr input array
  21. * @param toRemoveArr array of elements to be removed
  22. */
  23. export const removeFromArray = (inputArr, toRemoveArr) => {
  24. return inputArr.filter((x) => !toRemoveArr.includes(x));
  25. };
  26. /**
  27. * Returns the difference between two arrays, which match input array pattern
  28. * @param inputArr input array
  29. * @param toRemoveArr array of elements to be removed
  30. */
  31. export const removeIfMatchPattern = (inputArr, toRemoveArr) => {
  32. const matchedArr = matcher(inputArr, toRemoveArr);
  33. return removeFromArray(inputArr, matchedArr);
  34. };