Commit 4bd158e

mo khan <mo@mokhan.ca>
2013-11-07 04:40:39
sort by title ascending and descending.
1 parent d2b3dc7
lib/movie_library.js
@@ -129,6 +129,30 @@ module.exports = MovieLibrary = (function(_super) {
     });
   };
 
+  MovieLibrary.prototype.sort_by_title_ascending = function() {
+    return this.movies.sort(function(x, y) {
+      if (x.title > y.title) {
+        return 1;
+      }
+      if (x.title < y.title) {
+        return -1;
+      }
+      return 0;
+    });
+  };
+
+  MovieLibrary.prototype.sort_by_title_descending = function() {
+    return this.movies.sort(function(y, x) {
+      if (x.title > y.title) {
+        return 1;
+      }
+      if (x.title < y.title) {
+        return -1;
+      }
+      return 0;
+    });
+  };
+
   return MovieLibrary;
 
 })(Module);
src/movie_library.coffee
@@ -66,3 +66,17 @@ module.exports = class MovieLibrary extends Module
     @find_all (movie) =>
       movie.year_published > 1982 && movie.year_published < 2003
 
+  sort_by_title_ascending: ->
+    @movies.sort (x, y) ->
+      return 1 if x.title > y.title
+      return -1 if x.title < y.title
+      return 0
+
+  sort_by_title_descending: ->
+    @movies.sort (y, x) ->
+      return 1 if x.title > y.title
+      return -1 if x.title < y.title
+      return 0
+
+
+
test/movie_library_spec.coffee
@@ -90,3 +90,17 @@ describe "MovieLibrary", ->
        results.should.include(@chasing_amy)
        results.should.include(@toy_story)
        results.should.include(@monsters_inc)
+
+  context "sorting movies", ->
+    beforeEach ->
+      @sut.add(movie) for movie in @all_movies
+
+    it "sorts all movies by title ascending", ->
+      expected_order = [ @cars, @chasing_amy, @dumbo, @fantasia, @man_on_fire, @monsters_inc, @pinocchio, @shawshank_redemption, @toy_story, @up ]
+      results = @sut.sort_by_title_ascending()
+      results.should.eql(expected_order)
+
+    it "sorts all movies by title descending", ->
+      expected_order = [ @up, @toy_story, @shawshank_redemption, @pinocchio, @monsters_inc, @man_on_fire, @fantasia, @dumbo, @chasing_amy, @cars ]
+      results = @sut.sort_by_title_descending()
+      results.should.eql(expected_order)