My current requirement involves sorting collections easily, and I have decided to extend the Array primitive for this purpose. While I understand that extending built-in objects like Array is generally discouraged, it will only be used internally and not shared as a library. Despite multiple attempts with different approaches, I am unable to achieve the desired outcome, even though the function behaves correctly as expected in the TypeScript playground.
I initially attempted to add the polyfill directly in the /src/polyfills.ts file. However, this led to a "TypeError: Attempted to assign to readonly property" error in the console when invoking 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;
});
}
})
}
Another approach I explored was adding a plain JavaScript version via npm and importing it, which resulted in the same type error. What could be causing this issue?
/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"
],
...
}
],
...
}