Frontend Development 18 min read

Minimal Inventory in E‑commerce: SKU and Algorithm Implementation

This article explains the theory and practice of handling SKU (Stock Keeping Unit) in e‑commerce platforms, covering product creation, cart selection, Cartesian‑product based SKU generation, adjacency‑matrix and set‑theory approaches, and provides complete JavaScript implementations for front‑end developers.

政采云技术
政采云技术
政采云技术
Minimal Inventory in E‑commerce: SKU and Algorithm Implementation

Preface

In any e‑commerce platform that sells products, SKU management is inevitable. This article walks you through the theory and practice of SKU‑related core algorithms, from product creation to purchase, with hands‑on examples.

When a user selects specifications, the pre‑processed data helps them instantly see whether the product can be purchased.

During development, the product creation page assembles specification groups into a SKU set, while the purchase page processes specification selection to compute inventory and determine SKU availability.

Assembling SKU – Practice

Attribute Description

According to Baidu Baike, a SKU (Stock Keeping Unit) is the smallest unit for inventory control, often representing a combination of attributes such as size, color, and style.

Business Scenario

Any e‑commerce product (shopping app, website, etc.) faces the scenario where each product has multiple specifications, and users can combine them to choose the desired variant.

Example specifications:

const type = ["男裤", "女裤"]
const color = ["黑色", "白色"]
const size = ["S", "L"]

All possible SKUs generated from the above specifications:

[
  ["男裤", "黑色", "S"],
  ["男裤", "黑色", "L"],
  ["男裤", "白色", "S"],
  ["男裤", "白色", "L"],
  ["女裤", "黑色", "S"],
  ["女裤", "黑色", "L"],
  ["女裤", "白色", "S"],
  ["女裤", "白色", "L"]
]

SKU Combination – Cartesian Product

Cartesian Product

The Cartesian product of two sets X and Y, denoted X × Y, contains all ordered pairs (x, y) where x ∈ X and y ∈ Y. This satisfies the combinatorial requirement for SKU generation.

Implementation of Cartesian product in JavaScript:

/**
 * Cartesian product assembly
 * @param {Array} list
 * @returns []
 */
function descartes(list) {
  let point = {};
  let result = [];
  let pIndex = null;
  let tempCount = 0;
  let temp = [];
  // 1. Build pointer object based on input list
  for (let index in list) {
    if (typeof list[index] === 'object') {
      point[index] = { parent: pIndex, count: 0 };
      pIndex = index;
    }
  }
  // Single‑dimensional data returns directly
  if (pIndex === null) {
    return list;
  }
  // 2. Dynamically generate Cartesian product
  while (true) {
    let index;
    for (index in list) {
      tempCount = point[index].count;
      temp.push(list[index][tempCount]);
    }
    result.push(temp);
    temp = [];
    // 3. Move pointers
    while (true) {
      if (point[index].count + 1 >= list[index].length) {
        point[index].count = 0;
        pIndex = point[index].parent;
        if (pIndex === null) {
          return result;
        }
        index = pIndex;
      } else {
        point[index].count++;
        break;
      }
    }
  }
}

Multi‑Specification Selection

When a user selects a specification, the system must recalculate the availability of other specifications based on the remaining SKUs.

Initialization provides a list of selectable SKUs; each selection removes incompatible SKUs, and the process repeats until all specifications are chosen.

Adjacency Matrix

An adjacency matrix stores the relationship between vertices (specifications). A value of 1 indicates a connection (i.e., the two specifications can coexist in a SKU), while 0 indicates incompatibility.

Using the adjacency matrix, we can quickly determine which specification combinations are valid.

Set Theory Approach

Each specification is mapped to a unique prime number. A SKU is represented by the product of its specification primes. To check if a set of selected specifications is a subset of a SKU, we simply test whether the SKU product is divisible by the product of the selected primes.

Core steps:

Assign a distinct prime to each specification.

Pre‑compute the product for every SKU.

When a user selects a specification, multiply its prime with the product of already selected primes.

Check divisibility against each SKU product to determine availability.

Core Code – Prime Generation

/**
 * Generate prime numbers
 * @param {Int} num  Range of primes needed
 * @returns {Array}
 */
function getPrime(num) {
  let i = 2;
  const arr = [];
  const isPrime = (number) => {
    for (let ii = 2; ii < number / 2; ++ii) {
      if (number % ii === 0) {
        return false;
      }
    }
    return true;
  };
  for (i; arr.length < total; ++i) {
    if (isPrime(i)) {
      arr.push(i);
    }
  }
  return arr;
}

Core Code – Initialization

/**
 * Initialization – clone data and set default selectable state
 */
init: function () {
  this.light = util.cloneTwo(this.maps, true);
  var light = this.light;
  // Default each rule is selectable (value 1)
  for (var i = 0; i < light.length; i++) {
    var l = light[i];
    for (var j = 0; j < l.length; j++) {
      this._way[l[j]] = [i, j];
      l[j] = 1;
    }
  }
  // Convert each SKU's prime list to a product value
  for (i = 0; i < this.openway.length; i++) {
    this.openway[i] = eval(this.openway[i].join('*'));
  }
  this._check();
},

Core Code – Check Availability

/**
 * Check if a specification can be selected, update adjacency matrix
 * @param {Boolean} isAdd  Whether a new selection is added
 */
_check: function (isAdd) {
  var light = this.light;
  var maps = this.maps;
  for (var i = 0; i < light.length; i++) {
    var li = light[i];
    var selected = this._getSelected(i);
    for (var j = 0; j < li.length; j++) {
      if (li[j] !== 2) {
        if (isAdd) {
          if (li[j]) {
            light[i][j] = this._checkItem(maps[i][j], selected);
          }
        } else {
          light[i][j] = this._checkItem(maps[i][j], selected);
        }
      }
    }
  }
  return this.light;
},

Core Code – Add / Remove Specification

/** Select a specification */
add: function (point) {
  point = point instanceof Array ? point : this._way[point];
  var val = this.maps[point[0]][point[1]];
  if (!this.light[point[0]][point[1]]) {
    throw new Error('this point [' + point + '] is no availabe, place choose an other');
  }
  if (val in this.selected) return;
  var isAdd = this._dealChange(point, val);
  this.selected.push(val);
  this.light[point[0]][point[1]] = 2;
  this._check(!isAdd);
},
/** Remove a selected specification */
remove: function (point) {
  point = point instanceof Array ? point : this._way[point];
  try { var val = this.maps[point[0]][point[1]]; } catch (e) {}
  if (val) {
    for (var i = 0; i < this.selected.length; i++) {
      if (this.selected[i] == val) {
        var line = this._way[this.selected[i]];
        this.light[line[0]][line[1]] = 1;
        this.selected.splice(i, 1);
      }
    }
    this._check();
  }
},

Conclusion

The article demonstrates how classic combinatorial concepts such as Cartesian product, adjacency matrices, and set theory can be applied to solve SKU combination problems in e‑commerce front‑ends, providing both theoretical insight and practical JavaScript implementations.

References

1. Set‑theory calculation approach – link

2. Regular‑expression matching implementation – link

3. Adjacency‑matrix concept – link

e‑commerceFrontendAlgorithmjavascriptcartesian productSKU
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.