I need the ability to easily sort collections and I've chosen to extend the Array primitive. I realize this is considered bad practice in most cases, but this will be used only internally (not a shared lib). No matter what approach I've tried I'm not getting a working result even though it works as expected in the playground.
I've tried adding the polyfill inline in /src/polyfills.ts
but that gives me a "TypeError: Attempted to assign to readonly property" in the console when I call the $sortBy
method...
declare global {
interface Array<T> {
$sortBy(sortKey:string): T[];
}
}
if (!Array.prototype['$sortBy']) {
Object.defineProperty(Array.prototype, '$sortBy', {
value: function(sortKey) {
return this.sort( function(a, b) { // TypeError here???
if (a[sortKey] < b[sortKey]) { return -1; }
if (a[sortKey] > b[sortKey]) { return 1; }
return 0;
});
}
})
}
I've also tried adding a plain javascript version via npm and importing but that gives me the same type error. What's the secret???
/node_modules/my-polyfills/sortBy.js
if (!Array.prototype.$sortBy) {
Object.defineProperties(Array.prototype, {
'$sortBy': {
value: function (sortKey) {
return this.sort(function (a, b) {
if (a[sortKey] < b[sortKey]) {
return -1;
}
if (a[sortKey] > b[sortKey]) {
return 1;
}
return 0;
});
}
}
});
}
.angular-cli.json
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": { ... },
"apps": [
{
...,
"scripts": [
"../node_modules/my-polyfills/sortBy.js",
"../node_modules/moment/moment.js"
],
...
}
],
...
}