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

/**
 * Count the number of common items between two comma delimited strings.
 * @method adventurejs#countCommonElements
 * @memberOf adventurejs
 * @param {Object} world
 */
adventurejs.countCommonElements = function Adventurejs_countCommonElements(
  str1,
  str2
) {
  // Split the strings into arrays
  const arr1 = str1.split(",").map((item) => item.trim());
  const arr2 = str2.split(",").map((item) => item.trim());

  // Convert one of the arrays to a Set for efficient lookup
  const set2 = new Set(arr2);

  // Count the common elements
  let commonCount = 0;
  for (let item of arr1) {
    if (set2.has(item)) {
      commonCount++;
    }
  }

  return commonCount;
};