Created
May 27, 2020 02:32
-
-
Save harrisonmalone/6469126a5430e7e4cabae4792a705938 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 movies = require('/home/movies'); | |
const users = require('/home/users'); | |
function topWatchlistedMoviesAmongFriends(user_id, users, movies) { | |
// get current user | |
const currentUser = users.find((user) => user.userId === user_id) | |
// return an empty array if a current user can't be found | |
if (!currentUser) { | |
return [] | |
} | |
// access array of friends of current user | |
const { friends } = currentUser | |
// get a list of shared movies between all friends | |
const sharedMovies = [] | |
movies.forEach((movie) => { | |
const { watchlist } = movie | |
friends.forEach((friend) => { | |
if (watchlist.includes(friend)) { | |
sharedMovies.push(movie) | |
} | |
}) | |
}) | |
// add a count property to each movie object to count how many friends have it in their list | |
for (let movie of sharedMovies) { | |
const count = sharedMovies.filter((m) => movie === m).length | |
movie.count = count | |
} | |
// make a set of unique movies, remove any duplicates | |
const sharedMoviesSet = new Set(sharedMovies) | |
// convert movies back into an array and sort them based on count | |
const uniqueMovies = Array.from(sharedMoviesSet).sort((a, b) => b.count - a.count) | |
// make a data structure of movie arrays based on count | |
const movieObj = {} | |
uniqueMovies.forEach((movie) => { | |
if (!movieObj[movie.count]) { | |
movieObj[movie.count] = [] | |
movieObj[movie.count].push(movie.title) | |
} else { | |
movieObj[movie.count].push(movie.title) | |
} | |
}) | |
// sort each movie array nested in the object and unshift it to the front of the array | |
let result = [] | |
for (let key in movieObj) { | |
movieObj[key] = movieObj[key].sort() | |
result.unshift(movieObj[key]) | |
} | |
// flatten the array to have a single array instead of an array of arrays | |
const flatArray = result.flat() | |
// return only 4 items if length is longer than 4 | |
if (flatArray.length > 4) { | |
return flatArray.slice(0, 4) | |
} else { | |
return flatArray | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment