|
|
@@ -2,22 +2,11 @@ import mongoose from 'mongoose';
|
|
|
|
|
|
type IObjectId = mongoose.Types.ObjectId;
|
|
|
const ObjectId = mongoose.Types.ObjectId;
|
|
|
-
|
|
|
-const castToString = (val: string | IObjectId) => {
|
|
|
- if (typeof val === 'string') {
|
|
|
- return val;
|
|
|
- }
|
|
|
-
|
|
|
- return val.toString();
|
|
|
-};
|
|
|
-
|
|
|
-export const compareObjectId = (id1: IObjectId | string, id2: IObjectId | string): boolean => {
|
|
|
- return castToString(id1) === castToString(id2);
|
|
|
-};
|
|
|
+type ObjectIdLike = IObjectId | string;
|
|
|
|
|
|
export const isIncludesObjectId = (arr: (IObjectId | string)[], id: IObjectId | string): boolean => {
|
|
|
- const _arr = arr.map(i => castToString(i));
|
|
|
- const _id = castToString(id);
|
|
|
+ const _arr = arr.map(i => i.toString());
|
|
|
+ const _id = id.toString();
|
|
|
|
|
|
return _arr.includes(_id);
|
|
|
};
|
|
|
@@ -28,21 +17,26 @@ export const isIncludesObjectId = (arr: (IObjectId | string)[], id: IObjectId |
|
|
|
* @param testIds Array of mongoose.Types.ObjectId
|
|
|
* @returns Array of mongoose.Types.ObjectId
|
|
|
*/
|
|
|
-export const excludeTestIdsFromTargetIds = (targetIds: (IObjectId | string)[], testIds: (IObjectId | string)[]): IObjectId[] => {
|
|
|
+export const excludeTestIdsFromTargetIds = <T extends { toString: any } = IObjectId>(
|
|
|
+ targetIds: T[], testIds: (IObjectId | string)[],
|
|
|
+): T[] => {
|
|
|
// cast to string
|
|
|
- const arr1 = targetIds.map(e => castToString(e));
|
|
|
- const arr2 = testIds.map(e => castToString(e));
|
|
|
+ const arr1 = targetIds.map(e => e.toString());
|
|
|
+ const arr2 = testIds.map(e => e.toString());
|
|
|
|
|
|
// filter
|
|
|
const excluded = arr1.filter(e => !arr2.includes(e));
|
|
|
-
|
|
|
// cast to ObjectId
|
|
|
- return excluded.map(e => new ObjectId(e));
|
|
|
+ const shouldReturnString = (arr: any[]): arr is string[] => {
|
|
|
+ return typeof arr[0] === 'string';
|
|
|
+ };
|
|
|
+
|
|
|
+ return shouldReturnString(targetIds) ? excluded : excluded.map(e => new ObjectId(e));
|
|
|
};
|
|
|
|
|
|
export const removeDuplicates = (objectIds: (IObjectId | string)[]): IObjectId[] => {
|
|
|
// cast to string
|
|
|
- const strs = objectIds.map(id => castToString(id));
|
|
|
+ const strs = objectIds.map(id => id.toString());
|
|
|
const uniqueArr = Array.from(new Set(strs));
|
|
|
|
|
|
// cast to ObjectId
|