add sort by function

This commit is contained in:
Ian Storm Taylor 2014-03-25 14:15:52 -07:00
parent 6ed0b022b2
commit d1806abe0c
8 changed files with 58 additions and 11 deletions

View file

@ -41,7 +41,7 @@ function plugin(opts){
});
/**
* Sort the collection.
* Sort the collections.
*/
keys.forEach(function(key){
@ -49,6 +49,10 @@ function plugin(opts){
var settings = opts[key];
var sort = settings.sortBy || 'date';
var col = metadata[key];
if ('function' == typeof sort) {
col.sort(sort);
} else {
col.sort(function(a, b){
a = a[sort];
b = b[sort];
@ -59,6 +63,8 @@ function plugin(opts){
if (a > b) return 1;
return 0;
});
}
if (settings.reverse) col.reverse();
});

View file

@ -0,0 +1 @@
one

View file

@ -0,0 +1 @@
three

View file

@ -0,0 +1 @@
two

View file

@ -0,0 +1,6 @@
---
collection: articles
title: Alpha
---
one

View file

@ -0,0 +1,6 @@
---
collection: articles
title: Gamma
---
three

View file

@ -0,0 +1,6 @@
---
collection: articles
title: Beta
---
two

View file

@ -72,6 +72,26 @@ describe('metalsmith-collections', function(){
});
});
it('should accept a "sortBy" function', function(done){
var metalsmith = Metalsmith('test/fixtures/sort');
metalsmith
.use(collections({ articles: { sortBy: sort }}))
.build(function(err){
if (err) return done(err);
var articles = metalsmith.metadata().articles;
assert.equal('Gamma', articles[0].title);
assert.equal('Beta', articles[1].title);
assert.equal('Alpha', articles[2].title);
done();
});
function sort(a, b){
a = a.title.slice(1);
b = b.title.slice(1);
return a > b ? 1 : -1;
}
});
it('should accept a "reverse" option', function(done){
var metalsmith = Metalsmith('test/fixtures/sort');
metalsmith