diff --git a/src/films.js b/src/films.js index 5612e66..71d0673 100644 --- a/src/films.js +++ b/src/films.js @@ -52,10 +52,20 @@ function orderByYear(array) { // Exercise 6: Calculate the average of the movies in a category -function moviesAverageByCategory() { +function moviesAverageByCategory(array) { + let { totalScore, numMovies } = array.reduce((acc, movie) => { + if (movie.genre) { + acc.totalScore += movie.score; + acc.numMovies++; + } + return acc; + }, { totalScore: 0, numMovies: 0 }); + return numMovies ? parseFloat((totalScore / numMovies).toFixed(2)) : 0; } + + // Exercise 7: Modify the duration of movies to minutes function hoursToMinutes() { diff --git a/tests/films.spec.js b/tests/films.spec.js index 05b42b4..cf34d2e 100644 --- a/tests/films.spec.js +++ b/tests/films.spec.js @@ -292,9 +292,47 @@ describe('Function "orderByYear"', () => { // Exercise 6 // YOUR CODE HERE. Test moviesAverageByCategory() + + describe('Function "moviesAverageByCategory"', () => { - it('ADD YOUR CODE IN films.spec.js file', () => { - expect(typeof hoursToMinutes).toBe('coffee'); + it('should be declared', () => { + expect(typeof moviesAverageByCategory).toBe('function'); + }); + + it('should return a number', () => { + expect(typeof moviesAverageByCategory(movies, 'Drama')).toBe('number'); + }); + + it('should be different from NaN', () => { + expect(moviesAverageByCategory(movies, 'Drama')).not.toBeNaN(); + }); + it(' should return the average score of movies selecting only the category. With 2 decimals! ', () => { + expect(moviesAverageByCategory([ + { + title: 'Paths of Glory', + year: 1957, + director: 'Stanley Kubrick', + duration: '1h 28min', + genre: ['Drama', 'War'], + score: 8.4 + }, + { + title: 'Django Unchained', + year: 2012, + director: 'Quentin Tarantino', + duration: '2h 45min', + genre: ['Drama', 'Western'], + score: 8.4 + }, + { + title: 'Pulp Fiction', + year: 1994, + director: 'Quentin Tarantino', + duration: '2h 34min', + genre: ['Crime', 'Drama'], + score: 8.9 + } + ], 'Drama')).toBe(8.57); }); });