Skip to content
Browse files

Added sort_by

  • Loading branch information...
1 parent 9f9bd8a commit ebd4e9d1b9badde762477c3fafab446e562ae56c @tj tj committed Aug 20, 2010
Showing with 18 additions and 4 deletions.
  1. +1 −0 Readme.md
  2. +13 −1 lib/ejs/filters.js
  3. +4 −3 test/ejs.test.js
View
1 Readme.md
@@ -93,6 +93,7 @@ Currently these filters are available:
- downcase
- upcase
- sort
+ - sort_by:'prop'
- size
- length
- plus:n
View
14 lib/ejs/filters.js
@@ -55,6 +55,19 @@ exports.sort = function(obj){
};
/**
+ * Sort the target `obj` by the given `prop` ascending.
+ */
+
+exports.sort_by = function(obj, prop){
+ return Object.create(obj).sort(function(a, b){
+ a = a[prop], b = b[prop];
+ if (a > b) return 1;
+ if (a < b) return -1;
+ return 0;
+ });
+};
+
+/**
* Size or length of the target `obj`.
*/
@@ -176,4 +189,3 @@ exports.reverse = function(obj){
exports.get = function(obj, prop){
return obj[prop];
};
-
View
7 test/ejs.test.js
@@ -198,14 +198,15 @@ module.exports = {
}));
},
- 'test filter js': function(assert){
+ 'test sort_by filter': function(assert){
var html = 'tj',
- str = '<%=: [users[0]] | first | get:"name" %>';
+ str = '<%=: users | sort_by:"name" | last | get:"name" %>';
assert.equal(html, ejs.render(str, {
locals: {
users: [
+ { name: 'guillermo' },
{ name: 'tj' },
- { name: 'guillermo' }
+ { name: 'mape' }
]
}
}));

0 comments on commit ebd4e9d

Please sign in to comment.
Something went wrong with that request. Please try again.