call(back)

Data Selection

A data set of gym sessions looks like this. Each row has the user's id, the session's duration in minutes, and the equipment used, in alphabetical order (there are only five kinds).

const sessions = [
  { user: 8, duration: 50, equipment: ["bench"] },
  { user: 7, duration: 150, equipment: ["dumbbell", "kettlebell"] },
  { user: 1, duration: 10, equipment: ["barbell"] },
  { user: 7, duration: 100, equipment: ["bike", "kettlebell"] },
  { user: 7, duration: 200, equipment: ["bike"] },
  { user: 2, duration: 200, equipment: ["treadmill"] },
  { user: 2, duration: 200, equipment: ["bike"] },
];

Implement selectData(sessions, options), which returns the sessions selected by these options:

  • user: only this user's sessions.
  • minDuration: only sessions at least this long.
  • equipment: only sessions that used at least one of these.
  • merge: when true, sessions of the same user become one row: durations summed, equipment combined, de-duplicated and sorted. Merged rows are ordered by each user's last position in the input, so the user sequence 8, 7, 1, 7, 7, 2, 2 becomes 8, 1, 7, 2. The other options filter the merged rows.

Without merge, rows keep their input order. Never modify the input objects.

selectData(sessions, { merge: true });
// [
//   { user: 8, duration: 50, equipment: ["bench"] },
//   { user: 1, duration: 10, equipment: ["barbell"] },
//   { user: 7, duration: 450, equipment: ["bike", "dumbbell", "kettlebell"] },
//   { user: 2, duration: 400, equipment: ["bike", "treadmill"] },
// ]
selectData(sessions, { merge: true, minDuration: 400 }); // users 7 and 2

Hints

Hint 1

Merge first, filter second: the options describe the rows that come out, and after a merge those rows are the merged ones.

Hint 2

A Map keeps insertion order. To make a user's position follow their last session, delete the entry and set it again each time that user appears.

Hint 3

Build new objects when merging — [...a, ...b] into a Set, then sort — so the input is never touched.

Asked at

Similar Problems6