2017-06-21 78 views
0

我有2个功能修改列表。该列表是对象的字段。这个对象有很多列表,我不想几次写同一个代码。我需要可重用的功能。Typescript - 摆脱我的功能样板

现在看起来象下面这样:

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); 
} 

回答

2

下面是如何,您可以创建两个通用功能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()); 
} 
+0

注意:如果对象的属性是键入的(它们应该在TypeScript中,但似乎不是从问题来判断),我相信会有一个试图将一个字符串的值赋给之前是一个数组的变量的问题(反之亦然)。 – Vintr

+1

@Vintr你在哪里看到用于字符串和数组值的相同变量?难道是你将'this.relatedProducts'与'this.product.relatedProducts'混合?或者我错过了什么? –

+0

的确我是。这种令人困惑的命名。 :) – Vintr

1

就像你说:你应该写一个通用的函数,接受任何形式的列表,并在其上执行的逻辑。然后,将所有列表放入一个数组中,并使用您编写的函数对其进行迭代。例如:

function stringifyArray(array: any[], separator: string): string { 
    if (!array) { // Checks for undefined, null, NaN, 0, empty string 
    return ''; 
    } 
    return array.join(separator); 
} 

const oldLists: any[][] = [ 
    this.orders, 
    this.relatedproducts 
] 

const newLists: string[] = []; 

for (let i = 0; i < oldLists.length; i++) { 
    newLists.push(stringifyArray(oldLists[i], ',')); 
} 

图如何定义通用的功能,你需要以同样的方式进行,然后在你的列表循环动作的其余部分。

顺便说一句,为列表和字符串化版本分别设置字段可能是个好主意。这样,你可能不必来回转换这么多。

另请注意,我的示例中的函数实际上是多余的,因为它重复了Array.prototype.join()中已存在的行为。非冗余代码将是:

const oldLists: any[][] = [ 
    this.orders, 
    this.relatedproducts 
] 

const newLists: string[] = []; 

for (let i = 0; i < oldLists.length; i++) { 
    newLists.push(oldLists[i].join(',')); 
}