Created
June 18, 2020 02:44
-
-
Save implicit-invocation/e0a5a724a3ed4bdd11a448faa94cc0b5 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
const mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost:27017/test', { | |
useNewUrlParser: true, | |
useUnifiedTopology: true | |
}); | |
const Score = mongoose.model( | |
'score', | |
{ | |
userId: String, | |
highScores: { | |
type: [Number], | |
default: [] | |
}, | |
highestScore: { | |
type: Number, | |
default: 0 | |
} | |
}, | |
'score' | |
); | |
const reportScore = async (userId, score) => { | |
let scoreRecord = await Score.findOne({ userId }); | |
if (!scoreRecord) { | |
scoreRecord = await Score.create({ | |
userId | |
}); | |
} | |
scoreRecord.highestScore = Math.max(scoreRecord.highestScore, score); | |
if (scoreRecord.highScores.length < 3) { | |
scoreRecord.highScores.push(score); | |
} else if (score > scoreRecord.highScores[0]) { | |
scoreRecord.highScores[0] = score; | |
scoreRecord.highScores.sort(); | |
} | |
return await scoreRecord.save(); | |
}; | |
const getUserHighScores = async userId => { | |
const scoreRecord = await Score.findOne({ userId }); | |
if (!scoreRecord) { | |
return []; | |
} | |
return scoreRecord.highScores; | |
}; | |
const getTopNScore = async n => { | |
const records = await Score.find().sort('-highestScore').limit(n); | |
const result = records.map(r => ({ | |
userId: r.userId, | |
score: r.highestScore | |
})); | |
return result; | |
}; | |
const userId = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; | |
const scores = [10, 11, 12, 8, 7, 11.5, 13, 9, 15]; | |
const test = async () => { | |
await Score.deleteMany({}); | |
for (let i = 0; i < userId.length; i++) { | |
const scoreRecord = await reportScore(userId[i], scores[i]); | |
console.log(await getTopNScore(5)); | |
} | |
}; | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment