We have an existing filterRecommendations function that takes two arguments:
The goal is to generate a list of unique product recommendations, ensuring that products the user has already purchased are not included.
Given that information, how can this code be improved?
function filterRecommendations(purchasedProducts, potentialRecommendations) { return potentialRecommendations.filter( (product) => !purchasedProducts.includes(product) ); } // Testing the function console.time("Recommendations"); 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]; const result = filterRecommendations( purchasedProducts, potentialRecommendations ); console.log(result); // [11, 12, 13, 14, 15] console.timeEnd("Recommendations"); // 0.34814453125 ms
function filterRecommendations(purchasedProducts, potentialRecommendations) { return potentialRecommendations.filter( (product) => !purchasedProducts.includes(product) ); }
We can improve this code by using a Set to store the purchasedProducts list. Because Set allows us to check for the existence of a value in constant time, we can avoid the linear time lookup that Array.includes requires. In theory, this should make the function significantly faster for large lists of products (but you should always benchmark your code to be sure).
function filterRecommendations( purchasedProducts, potentialRecommendations ) { const purchasedProductsSet = new Set(purchasedProducts); return potentialRecommendations.filter( (productId) => !purchasedProductsSet.has(productId) ); } console.time("Recommendations"); 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]; const result = filterRecommendations( purchasedProducts, potentialRecommendations ); console.log(result); // [11, 12, 13, 14, 15] console.timeEnd("Recommendations"); // 0.212890625 ms