Skip to content

Instantly share code, notes, and snippets.

@tuhuynh27
Last active July 22, 2019 05:15
Show Gist options
  • Save tuhuynh27/96093a924053f569a61c694a3fd543f5 to your computer and use it in GitHub Desktop.
Save tuhuynh27/96093a924053f569a61c694a3fd543f5 to your computer and use it in GitHub Desktop.
import { db } from "@models";
async function pair() {
try {
const matchingCollection = db.collection("matchings");
const notMatchedArr = await matchingCollection
.find({
matched: false
})
.toArray();
if (!notMatchedArr.length) {
return false;
}
const bookDetailsIdsUnique = makeDistictArray(notMatchedArr);
const queuesByBookDetails = bookDetailsIdsUnique.map(e => {
const bookDetailQueue = notMatchedArr.filter(el => {
return el.bookDetailId === e;
});
return bookDetailQueue;
});
queuesByBookDetails.forEach(aBookDetailQueue => {
const returnArr = aBookDetailQueue.filter(match => !match.bookId);
const requestArr = aBookDetailQueue.filter(match => match.bookId);
returnArr.sort((a, b) => b.time - a.time);
requestArr.sort((a, b) => b.time - a.time);
const shorterLength =
returnArr.length < requestArr.length
? returnArr.length
: requestArr.length;
if (!shorterLength) {
return false;
}
const loopByShorterLength = Array.from(Array(shorterLength));
loopByShorterLength.forEach((_, index) => {
const matchedReturner = returnArr[index];
const matchedRequester = requestArr[index];
pairUpdateQueue.addJob(matchedReturner, matchedRequester);
});
});
return true;
} catch (err) {
console.log("Error when pair: ", err);
throw err;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment