Skip to content

Commit

Permalink
added $.by()
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieul committed Mar 29, 2009
1 parent 4176cb3 commit ddde1ce
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
12 changes: 10 additions & 2 deletions specs/lib/array_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,16 @@
*/
(function () {
describe('Array functions', {
"should ...": function () {
value_of(true).should_be_true();
"should return a sort callback to order by object property": function () {
var zhanna = {name: 'Zhanna', age: 27},
ira = {name: 'Irina', age: 27},
brioche = {name: 'Brioche', age: 1},
mathieu = {name: 'Mathieu', age: 38},
func = $.by('age');

value_of(func(zhanna, mathieu)).should_be(-1);
value_of(func(zhanna, ira)).should_be(0);
value_of(func(zhanna, brioche)).should_be(1);
}
});
})();
27 changes: 23 additions & 4 deletions src/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,30 @@
*/
$.extend({
/*
* compact: ...
* by: Function by takes a member name string and an
* optional minor comparison function and returns
* a comparison function that can be used to sort an
* array of objects that contain that member. The
* minor comparison function is used to break ties
* when the o[name] and p[name] are equal.
* (Douglas Crockford - Javascript: The Good Parts)
*/
compact: function (array) {
return array;
by: function (name, minor) {
return function (o, p) {
var a, b;
if (o && p && typeof o === 'object' && typeof p === 'object') {
a = o[name];
b = p[name];
if (a === b) {
return typeof minor === 'function' ? minor(o, p) : 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}
throw { name: 'Error', message: 'Expected an object when sorting by ' + name };
};
}
});


0 comments on commit ddde1ce

Please sign in to comment.