Recommend Products

Benchmark created on


Setup

const purchasedProducts = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const potentialRecommendations = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

// ================= //

function filterRecommendations(purchasedProducts, potentialRecommendations) {
  return potentialRecommendations.filter(
    (product) => !purchasedProducts.includes(product)
  )
}

function filterRecommendationsFast(
  purchasedProducts,
  potentialRecommendations
) {
  const purchasedProductsSet = new Set(purchasedProducts);
  return potentialRecommendations.filter(
    (productId) => !purchasedProductsSet.has(productId)
  )
}

function filterRecommendationsFastest(
  purchasedProducts,
  potentialRecommendations
) {
  const purchasedProductsObj = {}
  for (let i = 0; i < purchasedProducts.length; i++) {
    purchasedProductsObj[purchasedProducts[i]] = 0
  }
  return potentialRecommendations.filter(
    (productId) => !(productId in purchasedProductsObj)
  )
}

function filterRecommendationsFastest2(
  purchasedProducts,
  potentialRecommendations
) {
  const result = []
  for (let i = 0; i < potentialRecommendations.length; i++) {
    const r = potentialRecommendations[i]
    let found = false
    for (let j = 0; j < purchasedProducts.length; j++) {
      if (r == purchasedProducts[j]) found = true
    }

    if(!found)
      result.push(r)
  }
  return result
}

function filterRecommendationsFastest3(
  purchasedProducts,
  potentialRecommendations
) {
  const result = []
  for (let i = 0; i < potentialRecommendations.length; i++) {
    const r = potentialRecommendations[i]
    let found = false
    for (let j = 0; j < purchasedProducts.length; j++) {
      if (r == purchasedProducts[j]){
         found = true
         break
      }
    }

    if(!found)
      result.push(r)
  }
  return result
}

Test runner

Ready to run.

Testing in
TestOps/sec
Slow
filterRecommendations(
  purchasedProducts,
  potentialRecommendations
)
ready
Fast
filterRecommendationsFast(
  purchasedProducts,
  potentialRecommendations
)
ready
Fastest
filterRecommendationsFastest(
  purchasedProducts,
  potentialRecommendations
)
ready
Fastest 2
filterRecommendationsFastest2(
  purchasedProducts,
  potentialRecommendations
)
ready
Fastest 3
filterRecommendationsFastest3(
  purchasedProducts,
  potentialRecommendations
)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.