Created
October 18, 2015 16:24
-
-
Save lamchau/b3c0f782e867e4dac22e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getPath(object, path) { | |
if (typeof object === 'undefined' || typeof path !== 'string') { | |
return undefined; | |
} | |
var index = path.trim().indexOf('.'); | |
if (index < 0) { | |
return object[path]; | |
} | |
var key = path.substr(0, index); | |
var next = path.substr(index + 1); | |
return getPath(object[key], next); | |
} | |
// const people = [{ | |
// name: "bob", | |
// title: "bossA", | |
// age: 42 | |
// },{ | |
// name: "bob", | |
// title: "boss", | |
// age: 42 | |
// }]; | |
// people.sort((a, b) => new ComparatorChain( | |
// "+age", | |
// "+name", | |
// "+title") | |
// .compare(a, b)); | |
// console.log(JSON.stringify(people, null, 2)); | |
const ASCENDING = "+"; | |
const DESCENDING = "-"; | |
const EQUAL = 0; | |
const BEFORE = -1; | |
const AFTER = 1; | |
class ComparatorChain { | |
constructor(...properties) { | |
this.properties = Array.from(properties) | |
.map(property => this._parseProperty(property)); | |
} | |
_parseProperty(property) { | |
if (_.isFunction(property)) { | |
return property; | |
} | |
const direction = property.charAt(0); | |
const hasDirection = direction === ASCENDING || direction === DESCENDING; | |
return { | |
direction: hasDirection ? direction : ASCENDING, | |
propertyName: hasDirection ? property.slice(1) : property | |
}; | |
} | |
compare(a, b) { | |
let result = EQUAL; | |
for (const property of this.properties) { | |
if (_.isFunction(property)) { | |
result = property.call(this, a, b); | |
} else { | |
result = this.compareProperty(a, b, property); | |
} | |
if (result !== EQUAL) { | |
break; | |
} | |
} | |
return result; | |
} | |
compareProperty(a, b, { propertyName, direction }) { | |
// const propertyA = Ember.get(a, propertyName); | |
// const propertyB = Ember.get(b, propertyName); | |
const propertyA = getPath(a, propertyName); | |
const propertyB = getPath(b, propertyName); | |
if (propertyA === propertyB) { | |
return EQUAL; | |
} | |
if (direction === ASCENDING) { | |
return propertyA > propertyB ? AFTER : BEFORE; | |
} | |
return propertyA < propertyB ? AFTER : BEFORE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment