JSFiddle - React, Tailwind, and code Playground

by Pritesh Patel

JavaScript

// Define ad slots
const adSlots = [
  { slotId: 1, targeting: { demographics: 'male', location: 'us' } },
  { slotId: 2, targeting: { demographics: 'female', location: 'us' } },
  { slotId: 3, targeting: { demographics: 'all', location: 'us' } }
];

// Define ads
const ads = [
  { adId: 1, targeting: { demographics: 'male', location: 'us' }, bidAmount: 5.0 },
  { adId: 2, targeting: { demographics: 'male', location: 'us' }, bidAmount: 6.0 },
  { adId: 3, targeting: { demographics: 'female', location: 'us' }, bidAmount: 4.0 },
  { adId: 4, targeting: { demographics: 'female', location: 'us' }, bidAmount: 7.0 },
  { adId: 5, targeting: { demographics: 'all', location: 'us' }, bidAmount: 8.0 },
  { adId: 6, targeting: { demographics: 'all', location: 'us' }, bidAmount: 9.0 }
];

// Function to check if ad matches the slot's targeting criteria
function isAdMatching(slotTargeting, adTargeting) {
  const demographicsMatch = slotTargeting.demographics === 'all' || slotTargeting.demographics === adTargeting.demographics;
  const locationMatch = slotTargeting.location === adTargeting.location;
  return demographicsMatch && locationMatch;
}

// Function to match ads to slots
function matchAdsToSlots(adSlots, ads) {
  const allocation = [];

  for (const slot of adSlots) {
    // Filter ads that match the targeting criteria
    const matchingAds = ads.filter(ad => isAdMatching(slot.targeting, ad.targeting));

    if (matchingAds.length > 0) {
      // Select the ad with the highest bid amount
      const highestBidAd = matchingAds.reduce((prev, current) =>
        (prev.bidAmount > current.bidAmount) ? prev : current
      );

      allocation.push({ slotId: slot.slotId, adId: highestBidAd.adId });
    }
  }

  return allocation;
}

// Allocate ads to slots
const allocatedAds = matchAdsToSlots(adSlots, ads);
console.log(allocatedAds);