Created
May 4, 2020 01:44
-
-
Save b-coimbra/b9f9c509e0e38c405d49f32ab64c364c to your computer and use it in GitHub Desktop.
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
// 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