DEV Community

Amelia
Amelia

Posted on

A Beginner's Guide to JavaScript Size Recommendations

Have you ever wondered how to build a simple size recommendation engine for an e-commerce store? Today, I'll walk through a lightweight JavaScript implementation that suggests jean sizes based on customer measurements. This isn't production-ready, but it's a fun way to understand recommendation logic.

First, let's define our data structure. We'll store jean size charts as an array of objects, each containing waist and hip measurements in inches:

const jeanSizes = [
  { size: '24', waist: 24, hip: 34 },
  { size: '25', waist: 25, hip: 35 },
  { size: '26', waist: 26, hip: 36 },
  // ... up to size 36
];
Enter fullscreen mode Exit fullscreen mode

Now, the core recommendation function. We'll calculate Euclidean distance between the user's measurements and each size's ideal fit:

function recommendSize(userWaist, userHip) {
  let bestMatch = null;
  let smallestDistance = Infinity;

  for (const size of jeanSizes) {
    const distance = Math.sqrt(
      Math.pow(userWaist - size.waist, 2) + 
      Math.pow(userHip - size.hip, 2)
    );

    if (distance < smallestDistance) {
      smallestDistance = distance;
      bestMatch = size.size;
    }
  }

  return bestMatch;
}

// Example: User with 27" waist and 37" hips
console.log(recommendSize(27, 37)); // Likely returns '27'
Enter fullscreen mode Exit fullscreen mode

But real jeans shopping isn't just about measurements. Fit preference matters. Let's add a simple weighted system:

function advancedRecommend(userWaist, userHip, preference = 'regular') {
  const weights = {
    'slim': { waist: 0.7, hip: 0.3 },
    'regular': { waist: 0.5, hip: 0.5 },
    'relaxed': { waist: 0.3, hip: 0.7 }
  };

  const weight = weights[preference];
  let bestMatch = null;
  let smallestDistance = Infinity;

  for (const size of jeanSizes) {
    const distance = Math.sqrt(
      weight.waist * Math.pow(userWaist - size.waist, 2) + 
      weight.hip * Math.pow(userHip - size.hip, 2)
    );

    if (distance < smallestDistance) {
      smallestDistance = distance;
      bestMatch = size.size;
    }
  }

  return bestMatch;
}
Enter fullscreen mode Exit fullscreen mode

This approach works surprisingly well for a quick prototype. You could extend it with machine learning for more accurate predictions, but for a small catalog, this simple distance calculation does the job.

Of course, implementing this on a real site requires more robust data. For a practical example, I've seen this logic applied on sites like Frishay's women's jeans collection, where they use similar algorithms to help customers find the perfect fit across different brands and styles. The key is having accurate size charts and letting users input their measurements naturally.

Try extending this with your own size data and see how it performs. Happy coding!

Top comments (0)