Pre-release
AdventureJS Docs Downloads
Score: 0 Moves: 0
//hasDuplicates.js
/*global adventurejs A*/

/**
 * Takes an array and returns whether it contains any duplicate items.
 * @method adventurejs#hasDuplicates
 * @memberOf adventurejs
 * @param {Array} array
 * @param {String} string
 * @returns {Boolean}
 */
adventurejs.hasDuplicates = function Adventurejs_hasDuplicates(
  array,
  specificItem
) {
  if (!Array.isArray(array)) {
    console.warn("hasDuplicates.js received something that's not an array. ");
    return false;
  }
  const seenItems = new Set();

  if (specificItem !== undefined) {
    let specificItemCount = 0;
    for (let item of array) {
      if (item === specificItem) {
        specificItemCount++;
        if (specificItemCount > 1) {
          return true; // The specific item is found more than once
        }
      }
    }
    return false; // The specific item is not found more than once
  } else {
    for (let item of array) {
      if (seenItems.has(item)) {
        return true; // An item is found more than once
      }
      seenItems.add(item);
    }
    return false; // No duplicates found
  }
};