Skip to content

Instantly share code, notes, and snippets.

@airportyh
Last active December 11, 2015 06:38
Show Gist options
  • Select an option

  • Save airportyh/4560501 to your computer and use it in GitHub Desktop.

Select an option

Save airportyh/4560501 to your computer and use it in GitHub Desktop.
A quick compareBy function for easy configurable array sorting, with specs below.
function compareBy(){
var props = arguments
var numProps = arguments.length
return function(one, other){
for (var i = 0; i < numProps; i++){
var asc = true
var prop = props[i]
if (prop.charAt(0) === '^') prop = prop.substring(1)
if (prop.charAt(0) === '_'){
asc = false
prop = prop.substring(1)
}
var oneProp = one[prop]
var otherProp = other[prop]
if (oneProp > otherProp) return asc ? 1 : -1
else if (oneProp < otherProp) return asc ? -1 : 1
}
return 0
}
}
describe('compareBy', function(){
it('sorts one prop', function(){
var browsers = [
{name: 'Firefox'},
{name: 'Chrome'}
]
expect(browsers.sort(compareBy('name'))).to.deep.equal([
{name: 'Chrome'},
{name: 'Firefox'}
])
})
it('sorts ascending (also is default)', function(){
var browsers = [
{name: 'Firefox'},
{name: 'Chrome'}
]
expect(browsers.sort(compareBy('^name'))).to.deep.equal([
{name: 'Chrome'},
{name: 'Firefox'}
])
})
it('sorts descending (also is default)', function(){
var browsers = [
{name: 'Chrome'},
{name: 'Firefox'}
]
expect(browsers.sort(compareBy('_name'))).to.deep.equal([
{name: 'Firefox'},
{name: 'Chrome'}
])
})
it('sorts two props', function(){
var browsers = [
{name: 'Firefox', version: 15},
{name: 'Chrome', version: 20},
{name: 'Chrome', version: 14}
]
expect(browsers.sort(compareBy('^name', '_version'))).to.deep.equal([
{name: 'Chrome', version: 20},
{name: 'Chrome', version: 14},
{name: 'Firefox', version: 15}
])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment