1+ // Sample data for content-based filtering
2+ const movies = [
3+ {
4+ title : "The Dark Knight" ,
5+ genre : "Action" ,
6+ rating : 9.0 ,
7+ director : "Christopher Nolan"
8+ } ,
9+ {
10+ title : "Inception" ,
11+ genre : "Thriller" ,
12+ rating : 8.8 ,
13+ director : "Christopher Nolan"
14+ } ,
15+ {
16+ title : "The Godfather" ,
17+ genre : "Crime" ,
18+ rating : 9.2 ,
19+ director : "Francis Ford Coppola"
20+ } ,
21+ {
22+ title : "The Shawshank Redemption" ,
23+ genre : "Drama" ,
24+ rating : 9.3 ,
25+ director : "Frank Darabont"
26+ }
27+ ] ;
28+
29+ // Define the user's preferences
30+ const userPreferences = {
31+ genre : "Action" ,
32+ director : "Christopher Nolan"
33+ } ;
34+
35+ // Define a function to compute the similarity between movies
36+ function similarity ( movie , userPreferences ) {
37+ let similarityScore = 0 ;
38+ if ( movie . genre === userPreferences . genre ) {
39+ similarityScore += 1 ;
40+ }
41+ if ( movie . director === userPreferences . director ) {
42+ similarityScore += 1 ;
43+ }
44+ return similarityScore ;
45+ }
46+
47+ // Implement the content-based filtering algorithm
48+ function contentBasedFiltering ( movies , userPreferences ) {
49+ // Compute the similarity between each movie and the user's preferences
50+ const similarityScores = movies . map ( movie => {
51+ return {
52+ movie : movie ,
53+ score : similarity ( movie , userPreferences )
54+ } ;
55+ } ) ;
56+
57+ // Sort the movies by similarity score in descending order
58+ const sortedMovies = similarityScores . sort ( ( a , b ) => {
59+ return b . score - a . score ;
60+ } ) ;
61+
62+ // Return the top 3 movies with the highest similarity score
63+ return sortedMovies . slice ( 0 , 3 ) . map ( movie => movie . movie . title ) ;
64+ }
65+
66+ // Test the content-based filtering algorithm
67+ const recommendedMovies = contentBasedFiltering ( movies , userPreferences ) ;
68+ console . log ( recommendedMovies ) ; // Output: ["The Dark Knight", "Inception"]
0 commit comments