interface Identifiable {
  id?: string | number;
  [key: string]: any;
}

export function getObjectId(
  savedList: Identifiable[] = [],
  newList: Identifiable[] = [],
  key: string
): Identifiable[] {
  if (!newList.length) {
    return [];
  }

  if (!savedList.length) {
    return newList;
  }

  const savedItemsMap = new Map();
  savedList.forEach((item) => {
    if (item[key] !== undefined) {
      savedItemsMap.set(item[key], item.id);
    }
  });

  return newList.map((item) => {
    const id =
      item[key] !== undefined ? savedItemsMap.get(item[key]) : undefined;
    return {
      ...item,
      ...(id !== undefined ? { id } : {}),
    };
  });
}
