Last active
July 22, 2019 05:15
-
-
Save tuhuynh27/96093a924053f569a61c694a3fd543f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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