FlatMapSet VS MapReduce (v3)

Revision 3 of this benchmark created on


Setup

const randomId = () => Math.floor(Math.random() * 10000).toString();

const countryCodes = ['US', 'GR', 'DE', 'FR', 'IT', 'ES', 'NL'];
const languages = ['en', 'de', 'fr', 'it', 'es', 'nl', 'el'];
const benefitValues = ['Health Insurance', 'Retirement Plan', 'Vacation Days', 'Remote Work', 'Childcare', 'Training', 'Bonus', 'Flexible Hours', 'Gym Membership', 'Stock Options', 'Transportation Allowance', 'Meal Vouchers', 'Life Insurance', 'Disability Insurance', 'Dental Coverage', 'Vision Coverage', 'Professional Development', 'Employee Discounts', 'Sabbatical Leave', 'Wellness Programs'];

const getRandomElement = arr => arr[Math.floor(Math.random() * arr.length)];

const getRandomValues = () => {
  const count = Math.floor(Math.random() * 21); // Random number between 0 and 20
  const shuffled = benefitValues.sort(() => 0.5 - Math.random());
  return shuffled.slice(0, count);
};

const generateRandomData = (count = 5) => {
  const data = [];

  for (let i = 0; i < count; i++) {
    const attributes = {
      country_code: getRandomElement(countryCodes),
      language: getRandomElement(languages),
    };

    const valuesArray = getRandomValues();
    if (valuesArray.length > 0) {
      attributes.values = valuesArray;
    }

    data.push({
      attributes,
      id: randomId(),
      type: 'benefit',
    });
  }

  return data;
};

// Example usage:
const data = generateRandomData(100);

Test runner

Ready to run.

Testing in
TestOps/sec
FlatMapSet
const selectBenefitsForEntry = entry => entry?.attributes?.values ?? [];

const aggregateBenefits = data => {
  return [...new Set(data.flatMap(selectBenefitsForEntry))];
};

aggregateBenefits(data);
ready
MapReduce
const selectBenefitsForEntry = entry => entry?.attributes?.values ?? [];

const addUniqueBenefitsToExistingCollection = (existingCollection, benefits) => {
  benefits.forEach(benefit => {
    if (!existingCollection.includes(benefit)) {
      existingCollection.push(benefit);
    }
  });

  return existingCollection;
};

const aggregateBenefits = data => {
  return data.map(selectBenefitsForEntry).reduce(addUniqueBenefitsToExistingCollection, []);
};

aggregateBenefits(data);
ready
Set
const selectBenefitsForEntry = entry => entry?.attributes?.values ?? [];

const addUniqueBenefitsToExistingCollection = (existingCollection, benefits) => {
  return Array.from(new Set(existingCollection.concat(benefits)));
};

const aggregateBenefits = data => {
  return data.map(selectBenefitsForEntry).reduce(addUniqueBenefitsToExistingCollection, []);
};

aggregateBenefits(data);
ready

Revisions

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