Moh*_*mad 3 string coldfusion refactoring list
以下函数将新项目列表与旧项目列表进行比较,并找出差异:
我写了两个循环来实现这一点,他们产生了以下输出:
oldItems ="an,old,list"--->要删除的项目:'an,old'
newItems ="a,new,list"--->要创建的项目:'new'
第一个问题a应该出现在要创建的项目中,但是我相信因为它是一个an不能被拾取的子串.
第二个问题(?)是我做两个循环似乎效率低下.代码可以重构吗?
public function testList() hint="Compares two lists to find the differences."
{
local.oldItems = "a, new, list";
local.newItems = "an, old, list";
local.toDelete = "";
local.toCreate = "";
// Loop over newItems to find items that do not exist in oldItems
for (local.i = 1; local.i LTE ListLen(local.newItems, ", "); local.i++)
{
if (! ListContains(local.oldItems, ListGetAt(local.newItems, local.i, ", ")))
{
local.toCreate = ListAppend(local.toCreate, ListGetAt(local.newItems, local.i, ", "));
}
}
// Loop over old items to find items that do not exist in newItems
for (local.i = 1; local.i LTE ListLen(local.oldItems, ", "); local.i++)
{
if (! ListContains(local.newItems, ListGetAt(local.oldItems, local.i, ", ")))
{
local.toDelete = ListAppend(local.toDelete, ListGetAt(local.oldItems, local.i, ", "));
}
}
writeDump(var="Items To Delete: '" & local.toDelete & "'");
writeDump(var="Items To Create: '" & local.toCreate & "'", abort=true);
}
Run Code Online (Sandbox Code Playgroud)
是的,我相信你可以重构你的代码.
我更喜欢使用数组函数,因为它完全匹配(包括大小写).此方法确保将"a"作为列表之间的差异.
希望这可以帮助:
<cfscript>
oldList = "an, old, list";
newList = "a, new, list";
result = compareLists(oldList, newList);
writeDump(result);
// -------------------------------------------------------------------------
public struct function compareLists (
required string listA,
required string listB
){
local.a = listToArray(arguments.listA, ',');
local.b = listToArray(arguments.listB, ',');
local.itemsNotInListB = [];
local.itemsNewInListB = [];
// Compare all items in 'list A' to 'list B'
for (local.item in local.a) {
if (!arrayContains(local.b, local.item))
{
arrayAppend(local.itemsNotInListB, local.item);
}
}
// Compare all items in 'list B' to 'list A'
for (local.item in local.b) {
if (!arrayContains(local.a, local.item))
{
arrayAppend(local.itemsNewInListB, local.item);
}
}
return {
newItems = local.itemsNewInListB
,deletedItems = local.itemsNotInListB
};
}
</cfscript>
Run Code Online (Sandbox Code Playgroud)