Skip to content

arraypress/cartesian-product

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@arraypress/cartesian-product

Generate all combinations from arrays of options. Perfect for e-commerce variant generation, configuration matrices, and test case generation. Zero dependencies.

Works in Node.js, Cloudflare Workers, Deno, Bun, and browsers.

Install

npm install @arraypress/cartesian-product

Functions

cartesian(...arrays)

Generate the cartesian product of multiple arrays.

import { cartesian } from '@arraypress/cartesian-product';

cartesian(['S', 'M', 'L'], ['Red', 'Blue'])
// [['S','Red'], ['S','Blue'], ['M','Red'], ['M','Blue'], ['L','Red'], ['L','Blue']]

cartesian(['S', 'M'], ['Red', 'Blue'], ['Cotton', 'Silk'])
// 8 combinations (2 x 2 x 2)

cartesianObject(options)

Generate combinations as objects with named keys. Ideal for variant generation.

import { cartesianObject } from '@arraypress/cartesian-product';

cartesianObject({ Size: ['S', 'M', 'L'], Color: ['Red', 'Blue'] })
// [
//   { Size: 'S', Color: 'Red' },
//   { Size: 'S', Color: 'Blue' },
//   { Size: 'M', Color: 'Red' },
//   { Size: 'M', Color: 'Blue' },
//   { Size: 'L', Color: 'Red' },
//   { Size: 'L', Color: 'Blue' },
// ]

cartesianCount(...arrays)

Count total combinations without generating them. Useful for validation before generating large sets.

import { cartesianCount } from '@arraypress/cartesian-product';

cartesianCount(['S', 'M', 'L'], ['Red', 'Blue'])          // 6
cartesianCount(['S', 'M'], ['Red', 'Blue'], ['Cotton'])    // 4

Use Cases

E-commerce variants:

const options = {
  Size: ['S', 'M', 'L', 'XL'],
  Color: ['Red', 'Blue', 'Black'],
  Material: ['Cotton', 'Polyester'],
};

// Check count first
const count = cartesianCount(...Object.values(options));
console.log(`${count} variants will be generated`); // 24

// Generate variant objects
const variants = cartesianObject(options);
// [{ Size: 'S', Color: 'Red', Material: 'Cotton' }, ...]

Test matrices:

const browsers = ['Chrome', 'Firefox', 'Safari'];
const devices = ['Desktop', 'Mobile', 'Tablet'];
const testCases = cartesian(browsers, devices);
// 9 test case combinations

License

MIT

About

Generate all combinations from arrays of options. Perfect for e-commerce variant generation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors