Skip to content

Commit

Permalink
enhancement: the sort now works on nested properties
Browse files Browse the repository at this point in the history
  • Loading branch information
gregorybesson committed Dec 25, 2016
1 parent 83e4d34 commit 9abffd1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/cli/core/utils/sort.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export function shuffle(array) {
* @return integer the ordered value
*/
export function predicatBy(prop, order){
prop = prop.split('.')
var len = prop.length

if (order !== -1) {
order = 1
}
Expand All @@ -50,12 +53,14 @@ export function predicatBy(prop, order){
}
}

return function(a,b){
if( a[prop] > b[prop]){
return 1*order
}else if( a[prop] < b[prop] ){
return function (a, b) {
var i = 0
while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++ }
if (a < b) {
return -1*order
} else if (a > b) {
return 1*order
}
return 0
}
}
}
12 changes: 12 additions & 0 deletions test/core/utils/sort.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,16 @@ describe('Sort', function() {
var shuffled = coreUtils.sort.shuffle(list)
chai.expect(shuffled[0].name).to.be.oneOf(['article-2.json', 'article-1.json', 'homepage-1.json']);
});

it('coreUtils.sort.predicatBy 1', function() {
var list = Manager.instance.getList()
list.sort(coreUtils.sort.predicatBy('name', 1))
chai.expect(list[0].name).to.equal('article-1.json');
});

it('coreUtils.sort.predicatBy 2', function() {
var list = Manager.instance.getList()
list.sort(coreUtils.sort.predicatBy('abe_meta.template', -1))
chai.expect(list[0].abe_meta.template).to.equal('homepage');
});
});

0 comments on commit 9abffd1

Please sign in to comment.