const User = require('../model/user.js')
const Session = require('../model/session.js')

module.exports = (req, res, next) => {
  User.findOne({ username: req.params.username }).sort({ date: 'desc' }).exec()
    .then((user) => {
      return getSessions(user.sessions, req.params.number)
    })
    .then((sessions) => {
      return calculateScores(sessions)
    })
    .then((scores) => {
      return res.json({
        status: 'success',
        data: {
          scores: scores
        }
      })
    })
    .catch((err) => {
      console.error(err)
      return res.json({
        status: 'error',
        message: err
      })
    })

  next()
}

function getSessions(sessions, number) {
  if (number) sessions = sessions.slice(0, number)
  sessions = sessions.map((id) => { return Session.findById(id).exec() })
  return Promise.all(sessions)
}

function calculateScores(sessions) {
  let scores = []
  let shapeScores = []
  let mathScores = []
  let memoryScores = []

  sessions.forEach((session) => {
    let date = session.date

    shapeScores.push({ date: date, score: session.shapeGames.score })
    mathScores.push({ date: date, score: session.mathGames.score })
    memoryScores.push({ date: date, score: session.memoryGames.score })

    scores = {
      shapeScores: shapeScores,
      mathScores: mathScores,
      memoryScores: memoryScores
    }
  })

  return Promise.resolve(scores)
}

@@ -890,26 +890,8 @@
 ) %7B%0A
-  let scores = %5B%5D%0A
   le
@@ -1233,30 +1233,29 @@
  %7D)%0A
-%0A
   
-  scores =
+%7D)%0A%0A  return
  %7B%0A    
- 
- 
 shap
@@ -1280,18 +1280,16 @@
 es,%0A    
-  
 mathScor
@@ -1308,18 +1308,16 @@
 es,%0A    
- 
- 
 memorySc
@@ -1341,49 +1341,8 @@
 s%0A  
-  %7D%0A  %7D)%0A%0A  return Promise.resolve(scores)
+%7D
 %0A%7D%0A

Add bug fixes to scores.js