Skip to content

Instantly share code, notes, and snippets.

@thomaswrenn
Last active November 10, 2020 07:09
Show Gist options
  • Save thomaswrenn/b418e3a67f4a3ab0390da01b2adf97ea to your computer and use it in GitHub Desktop.
Save thomaswrenn/b418e3a67f4a3ab0390da01b2adf97ea to your computer and use it in GitHub Desktop.
Sorting Lodash vs Ember.computed.sort
import { sort } from '@ember/object/computed';
import { computed, get } from '@ember/object';
import { compare } from '@ember/utils';
import Controller from '@ember/controller';
import { sortBy } from 'lodash';
export default class ApplicationController extends Controller {
appName = 'Ember Twiddle';
items = [
{'name': 'MacGruff'},
{'name': 'McDuff'},
{'name': 'Mccet'},
{'name': 'McCharles'},
{'name': 'Merogh'},
{'name': 'Durnham'},
{'name': 'Dull'},
{'name': 'DuAlto'},
{'name': 'DuPertius'},
];
sortKeys = ['name'];
@sort('items', 'sortKeys')
sortedItems;
@computed('items', 'sortKeys')
get lodashSortedItems() {
let items = this.items;
if (items.toArray) {
items = items.toArray();
}
return sortBy(items, this.sortKeys.map((fieldKey) => {
return item => get(item, fieldKey);
}));
}
@computed('items', 'sortKeys')
get betterNonComputedSortSortedItems() {
let items = this.items;
if (items.toArray) {
items = items.toArray();
}
return items.sort((a, b) => {
return compare(
this.sortKeys.map((fieldKey) => get(a, fieldKey)),
this.sortKeys.map((fieldKey) => get(b, fieldKey))
);
});
};
}
<h1>Welcome to {{this.appName}}</h1>
<strong>Ember.computed.sort sorted items (This is the prefered method/order)</strong>
{{#each this.sortedItems as |item|}}
<div>{{item.name}}</div>
{{/each}}
<br>
<strong>lodash sortBy sorted items</strong>
{{#each this.lodashSortedItems as |item|}}
<div>{{item.name}}</div>
{{/each}}
<br>
<strong>better non-computed sort sorted items</strong>
{{#each this.betterNonComputedSortSortedItems as |item|}}
<div>{{item.name}}</div>
{{/each}}
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"ember-lodash": "4.19.5",
"@glimmer/component": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment