Last active
April 20, 2017 06:51
-
-
Save thomaswrenn/5ad858ebfd08e45e6590874100348af2 to your computer and use it in GitHub Desktop.
Comparing fixedSort and Ember.computed.sort behavior
This file contains 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
import Ember from 'ember'; | |
export function fixedSort(arrayProp, ...sortProps) { | |
console.log(arrayProp, sortProps); | |
let parsedProps = sortProps.map((prop) => { | |
let [name, dir] = prop.split(':'); | |
return [name, dir === 'desc' ? 1 : -1]; | |
}); | |
let observerString = `${arrayProp}.@each.{${parsedProps.map(prop => prop[0]).join(',')}}`; | |
function sortFn() { | |
let array = this.get(arrayProp) || []; | |
let sorted = array.slice(); | |
let nProps = parsedProps.length; | |
sorted.sort(function(a, b) { | |
let i = 0; | |
while (i < nProps && Ember.get(a, parsedProps[i][0]) === Ember.get(b, parsedProps[i][0])) { | |
i++; | |
} | |
if (i >= nProps) { | |
return 0; | |
} else if (Ember.get(a, parsedProps[i][0]) < Ember.get(b, parsedProps[i][0])) { | |
return parsedProps[i][1]; | |
} else { | |
return -parsedProps[i][1]; | |
} | |
}); | |
console.log(arrayProp, sortProps, sorted.mapBy('created')); | |
return sorted; | |
} | |
return Ember.computed.apply(Ember, [observerString, sortFn]); | |
} | |
export default Ember.Controller.extend({ | |
appName: 'Ember Twiddle', | |
sort: ['created:asc'], | |
items: [{created: undefined},{created: new Date(2017,1,15)},{created: new Date(2017,1,10)},{created: undefined},{created: new Date(2017,1,12)},{created: undefined}], | |
sortedItems: Ember.computed.sort('items', 'sort'), | |
fixedSortItems: fixedSort('items', 'created:asc') | |
}); |
This file contains 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
{ | |
"version": "0.12.1", | |
"EmberENV": { | |
"FEATURES": {} | |
}, | |
"options": { | |
"use_pods": false, | |
"enable-testing": false | |
}, | |
"dependencies": { | |
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js", | |
"ember": "2.12.0", | |
"ember-template-compiler": "2.12.0", | |
"ember-testing": "2.12.0" | |
}, | |
"addons": { | |
"ember-data": "2.12.1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment