compare-objectId.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import mongoose from 'mongoose';
  2. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  3. type IObjectId = mongoose.Types.ObjectId;
  4. const ObjectId = mongoose.Types.ObjectId;
  5. /**
  6. * Check if array contains all specified ObjectIds
  7. * @param arr array that potentially contains potentialSubset
  8. * @param potentialSubset array that is potentially a subset of arr
  9. * @returns Whether or not arr includes all elements of potentialSubset
  10. */
  11. export const includesObjectIds = (arr: ObjectIdLike[], potentialSubset: ObjectIdLike[]): boolean => {
  12. const _arr = arr.map(i => i.toString());
  13. const _potentialSubset = potentialSubset.map(i => i.toString());
  14. return _potentialSubset.every(id => _arr.includes(id));
  15. };
  16. /**
  17. * Check if 2 arrays have an intersection
  18. * @param arr1 an array with ObjectIds
  19. * @param arr2 another array with ObjectIds
  20. * @returns Whether or not arr1 and arr2 have an intersection
  21. */
  22. export const hasIntersection = (arr1: ObjectIdLike[], arr2: ObjectIdLike[]): boolean => {
  23. const _arr1 = arr1.map(i => i.toString());
  24. const _arr2 = arr2.map(i => i.toString());
  25. return _arr1.some(item => _arr2.includes(item));
  26. };
  27. /**
  28. * Exclude ObjectIds which exist in testIds from targetIds
  29. * @param targetIds Array of mongoose.Types.ObjectId
  30. * @param testIds Array of mongoose.Types.ObjectId
  31. * @returns Array of mongoose.Types.ObjectId
  32. */
  33. export const excludeTestIdsFromTargetIds = <T extends { toString: any } = IObjectId>(
  34. targetIds: T[], testIds: ObjectIdLike[],
  35. ): T[] => {
  36. // cast to string
  37. const arr1 = targetIds.map(e => e.toString());
  38. const arr2 = testIds.map(e => e.toString());
  39. // filter
  40. const excluded = arr1.filter(e => !arr2.includes(e));
  41. // cast to ObjectId
  42. const shouldReturnString = (arr: any[]): arr is string[] => {
  43. return typeof arr[0] === 'string';
  44. };
  45. return shouldReturnString(targetIds) ? excluded : excluded.map(e => new ObjectId(e));
  46. };