Skip to content

Instantly share code, notes, and snippets.

@thomaswrenn
Last active April 20, 2017 06:51
Show Gist options
  • Save thomaswrenn/5ad858ebfd08e45e6590874100348af2 to your computer and use it in GitHub Desktop.
Save thomaswrenn/5ad858ebfd08e45e6590874100348af2 to your computer and use it in GitHub Desktop.
Comparing fixedSort and Ember.computed.sort behavior
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')
});
<h1>Welcome to {{appName}}</h1>
{{#each sortedItems as |item|}}
<div>{{if item.created item.created 'undefined'}}</div>
{{/each}}
<br>
{{#each fixedSortItems as |item|}}
<div>{{if item.created item.created 'undefined'}}</div>
{{/each}}
<br>
{{outlet}}
<br>
<br>
{
"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