Permalink
Browse files

Implement sortBy.

  • Loading branch information...
mitukiii committed Mar 16, 2011
1 parent 587f1a1 commit cc609a739b6ea36d5a975b019be5bf6ad92a9a3d
Showing with 34 additions and 1 deletion.
  1. +14 −1 public/javascripts/jquery.enumerable.js
  2. +20 −0 spec/javascripts/jquery.enumrable_spec.js
@@ -113,14 +113,26 @@
return results;
};
+ var sortBy = function(enumerable, iterator) {
+ return $(enumerable).map(function(index, value) {
+ return {
+ value: value,
+ criteria: iterator.call(value, index, value)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }).pluck('value');
+ };
+
var pluck = function(enumerable, property) {
var results = [];
$.each(enumerable, function(index, value) {
results.push(value[property]);
});
return results;
};
-
+
return {
all: all,
any: any,
@@ -135,6 +147,7 @@
minBy: minBy,
partition: partition,
reject: reject,
+ sortBy: sortBy,
pluck: pluck
};
}();
@@ -199,4 +199,24 @@ describe('jquery.enumerable', function() {
expect($.pluck(arr, 'content')).toEqual(["content1", "content2"]);
});
});
+
+ describe('sortBy ["200", "30", "1000"]', function() {
+ var arr;
+
+ beforeEach(function() {
+ arr = ["200", "30", "1000"];
+ });
+
+ it('number string should be ["1000", "200", "30"]', function() {
+ expect($.sortBy(arr, function() {
+ return this;
+ })).toEqual(["1000", "200", "30"]);
+ });
+
+ it('parsed integer number should be ["30", "200", "1000"]', function() {
+ expect($.sortBy(arr, function() {
+ return parseInt(this);
+ })).toEqual(["30", "200", "1000"]);
+ });
+ });
});

0 comments on commit cc609a7

Please sign in to comment.