正确扩展数组原型



我有一个groupBy方法,我想用它来扩展Array。

const groupBy = <T>(array: T[], predicate: (value: T, index: number, array: T[]) => string) =>
array.reduce((acc, value, index, array) => {
(acc[predicate(value, index, array)] ||= []).push(value);
return acc;
}, {} as { [key: string]: T[] });

我在这里找到了这个方法,并试图使我的数组像const groupItems = myItems.groupBy(item => item.key)一样运行。

我有基本的扩展代码设置,以及一个已经应用的独特方法。我如何使用这个groupBy方法,并将其正确地应用为扩展,以便能够像const groupItems = myItems.groupBy(item => item.key)一样使用它?

现有扩展代码:

export { };
declare global {
interface Array<T> {
distinct(): Array<T>;
}
}
if (!Array.prototype.distinct) {
Array.prototype.distinct = function <T>(): T[] {
const stringifiedItems = this.map((item) => JSON.stringify(item));
const set = new Set(stringifiedItems);
return Array.from(set).map((item) => JSON.parse(item));
};
}

我能够用以下代码做到这一点:

export { };
declare global {
interface Array<T> {
distinct(): Array<T>;
// Add the interface declaration
groupBy(predicate: (value: T, index: number, array: T[]) => string): { [key: string]: T[] }
}
}
if (!Array.prototype.distinct) {
Array.prototype.distinct = function <T>(): T[] {
const stringifiedItems = this.map((item) => JSON.stringify(item));
const set = new Set(stringifiedItems);
return Array.from(set).map((item) => JSON.parse(item));
};
}
// Add it to the prototype
if (!Array.prototype.groupBy) {
Array.prototype.groupBy = function <T>(predicate: (value: T, index: number, array: T[]) => string) {
return this.reduce((acc, value, index, array) => {
(acc[predicate(value, index, array)] ||= []).push(value);
return acc;
}, {} as { [key: string]: T[] });
}
}

最新更新