簡體   English   中英

我怎樣才能改進我的代碼? 關於元素不重復

[英]How can i improve my code? about elements not repeat

我想知道該元素是否已經存在於我的列表中,因為我存在 function

function exist(colection,newItem,newIndex) {
    let theName = changeIndexOnName(newItem,newIndex)
    const exist =  colection.find( item =>(theName === item.name))
    return !!exist
}

我不想重復我的元素的名稱,這就是為什么我這樣列出它們:(element-1, element-2, element-3...element-n) by this function changeIndexOnName()。

function add(colection, newItem) {
    let allowedIndex = 0
    while(exist(colection, newItem, allowedIndex)){
      allowedIndex++
    }
    newItem.name = changeIndexOnName(newItem.name, allowedIndex)  
    colection.push(newItem)
    return colection
}

一旦我有可用的號碼,我就會在那里更改號碼的名稱。 newItem.name = changeIndexOnName(newItem.name, allowedIndex)

這是開始,我有兩個 arrays,我想將新元素放入舊元素列表中

for (const e of newElements) {
   add(olderElements, e)
}

您可以使用filter直接查找新索引let allowedIndex = colection.filter(item => item.name.split('-')[0] === newItem.name).length; .

在下面試試。

 let olderElements = [{name: "Collection"}]; let newElements = [{name: "Collection"}, {name: "Collection"}]; function changeIndexOnName(name, allowedIndex) { return name + (allowedIndex === 0? "": ("-" + allowedIndex)); } function add(colection, newItem) { let allowedIndex = colection.filter(item => item.name.split('-')[0] === newItem.name).length; newItem.name = changeIndexOnName(newItem.name, allowedIndex) colection.push(newItem) return colection; } for (const e of newElements) { add(olderElements, e); } console.log(olderElements);

如果我們沒有關於changeIndexOnName()內部的信息,那么先將所有現有名稱保存在一個集合中會更快。

function add(colection, newItem) {
  let names = new Set(collection.map(item => item.name))

  let newIndex = 0
  let newName = changeIndexOnName(newItem, newIndex)

  while(newName in names) {
    newName = changeIndexOnName(newItem, ++newIndex)
  }

  newItem.name = newName
  colection.push(newItem)

  return colection
}

但是,如果我們知道名稱是image-XX ,您可以使用一些正則表達式提取XX部分(在下面的示例中,我在 function extractIndex中使用了簡單的split

function add(colection, newItem) {
  const extractIndex = name => Number(item.name.split("-")[1])
  let maxIndex = Math.max(...collection.map(extractIndex))
  
  newItem.name = "image-" + (maxIndex+1)
  colection.push(newItem)

  return colection
}

上面的代碼找到最大索引,並使用max+1作為下一個索引。 請注意,在生產代碼中,您必須查找溢出和名稱解析錯誤。

如果我是你,我會:

  • 使用隨機唯一索引,例如由時間戳和隨機數組成
  • 如果存在索引沖突的風險,則將一組已分配的索引存儲在一個集合中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM