Skip to content

Instantly share code, notes, and snippets.

@b-coimbra
Created May 4, 2020 01:44
Show Gist options
  • Save b-coimbra/b9f9c509e0e38c405d49f32ab64c364c to your computer and use it in GitHub Desktop.
Save b-coimbra/b9f9c509e0e38c405d49f32ab64c364c to your computer and use it in GitHub Desktop.
// extensions.shared.ts
namespace global {
export interface Array<T> {
sortBy(modifier: string, isReverse: boolean): T[];
};
};
Array.prototype.sortBy = function (modifier: string, isReverse: boolean): User[] {
const isNumber = (x: string | number) => typeof x == 'number';
let sorted = this.sort((a: any, b: any) => {
if (isNumber(a[modifier]) && isNumber(a[modifier]))
return a > b;
return a[modifier].localeCompare(b[modifier]);
});
if (isReverse)
return sorted.reverse();
return sorted;
};
// */user.model.ts
interface User {
id: number
name: string
};
// *.component.ts
const users: User[] = [
{
id: 1,
name: 'Ambrose'
},
{
id: 2,
name: 'Brandon'
},
{
id: 3,
name: 'Charles'
}
];
// tests
// ordered by name
console.table(users.sortBy('name', false));
// ordered by name in reverse
console.table(users.sortBy('name', true));
// ordered by ID
console.table(users.sortBy('id', false));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment