gpt4 book ai didi

javascript - Typescript - 从我的函数中删除样板文件

转载 作者:行者123 更新时间:2023-11-28 17:55:03 24 4
gpt4 key购买 nike

我有两个修改列表的函数。该列表是对象的字段。这个对象有很多列表,我不想多次编写相同的代码。我需要可重用的功能。

现在看起来如下:

setLists(): void {
if (this.product.orders !== null) {
this.orders = this.product.orders.join(', ');
} else {
this.orders = '';
}

if (this.product.relatedProducts !== null) {
this.relatedProducts = this.product.relatedProducts.join(', ');
} else {
this.relatedProducts = '';
}
}

这里只有 2 个字段,但实际上产品有很多列表。我不想对每个列表重复相同的操作。

第二个样板函数如下所示:

updateProductLists(): void {
let splittedOrders: string[] = this.orders.split(",");
splittedOrders = splittedOrders.map(o => o.trim());
this.product.orders = new Array<string>();
this.project.orders.push(...splittedOrders);

let splittedRelatedProducts: string[] = this.relatedProducts.split(",");
splittedRelatedProducts = splittedRelatedProducts.map(r => r.trim());
this.product.relatedProducts = new Array<string>();
this.product.relatedProducts.push(...splittedRelatedProducts);
}

最佳答案

下面是一个示例,说明如何创建两个更通用的函数 listToStringstringToList 以及如何在代码中使用它们,而不是重写相同的内容及以上

// Your old method will now look like this
setLists(): void {
this.orders = this.listToString(this.product.orders);
this.relatedProducts = this.listToString(this.product.relatedProducts);
}

// Generic method for joining the arrays into strings the way you did
listToString(sourceList: any[]): string {
return sourceList ? sourceList.join(', ') : '';
}

// Your old method will now look like this
updateProductLists(): void {
this.product.orders = this.stringToList(this.orders);
this.product.relatedProducts = this.stringToList(this.relatedProducts);
}

// Generic method for splitting the strings into lists the way you did
stringToList(sourceString: string): any[] {
return sourceString.split(',').map(i => i.trim());
}

关于javascript - Typescript - 从我的函数中删除样板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44668992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com