Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7546901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T09:19:06+00:00 2026-05-30T09:19:06+00:00

There are other questions about this in other languages , and other non-lazy JavaScript

  • 0

There are other questions about this in other languages, and other non-lazy JavaScript versions, but no lazy JavaScript versions that I have found.

Given an array of an arbitrary number of arbitrary-sized arrays:

var sets = [ [2,3,4,5], ['sweet','ugly'], ['cats','dogs','hogs'] ];

and a callback function:

function holla( n, adj, noun ){
  console.log( [n,adj,noun].join(' ') );
}

what’s an elegant way to iterate the entire product space without creating a huge array of all possible combinations first?

lazyProduct( sets, holla );
// 2 sweet cats
// 2 sweet dogs
// 2 sweet hogs
// 2 ugly cats
// 2 ugly dogs
// 2 ugly hogs
// 3 sweet cats
// 3 sweet dogs
// 3 sweet hogs
// 3 ugly cats
// 3 ugly dogs
// 3 ugly hogs
// 4 sweet cats
// 4 sweet dogs
// 4 sweet hogs
// 4 ugly cats
// 4 ugly dogs
// 4 ugly hogs
// 5 sweet cats
// 5 sweet dogs
// 5 sweet hogs
// 5 ugly cats
// 5 ugly dogs
// 5 ugly hogs

Note that these combinations are the same as the results you would get if you had nested loops:

var counts     = [2,3,4,5];
var adjectives = ['sweet','ugly'];
var animals    = ['cats','dogs','hogs'];
for (var i=0;i<counts.length;++i){
  for (var j=0;j<adjectives.length;++j){
    for (var k=0;k<animals.length;++k){
      console.log( [ counts[i], adjectives[j], animals[k] ].join(' ') );
    }
  }
}

The benefits of the Cartesian product are:

  1. It lets you nest an arbitrary number of loops (perhaps you don’t know how many items you’ll iterate)
  2. It lets you change the order of looping (e.g. loop by adjectives first) without having to edit your code or write out all possible combinations of looping order.

Benchmarks

You can see the benchmarks for the answers below here:
http://jsperf.com/lazy-cartesian-product/26

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T09:19:07+00:00Added an answer on May 30, 2026 at 9:19 am

    Coincidentally working on the same thing over the weekend. I was looking to find alternative implementations to my [].every-based algo which turned out to have abyssmal performance in Firefox (but screams in Chrome — more than twice as fast as the next).

    The end result is http://jsperf.com/lazy-cartesian-product/19 . It’s similar to Tomalak’s approach but there is only one arguments array which is mutated as the carets move instead of being generated each time.

    I’m sure it could be improved further by using the clever maths in the other algos. I don’t quite understand them though, so I leave it to others to try.

    EDIT: the actual code, same interface as Tomalak’s. I like this interface because it could be breaked anytime. It’s only slightly slower than if the loop is inlined in the function itself.

    var xp = crossProduct([
      [2,3,4,5],['angry','happy'], 
      ['monkeys','anteaters','manatees']]);
    while (xp.next()) xp.do(console.log, console);
    
    function crossProduct(sets) {
      var n = sets.length, carets = [], args = [];
    
      function init() {
        for (var i = 0; i < n; i++) {
          carets[i] = 0;
          args[i] = sets[i][0];
        }
      }
    
      function next() {
        if (!args.length) {
          init();
          return true;
        }
        var i = n - 1;
        carets[i]++;
        if (carets[i] < sets[i].length) {
          args[i] = sets[i][carets[i]];
          return true;
        }
        while (carets[i] >= sets[i].length) {
          if (i == 0) {
            return false;
          }
          carets[i] = 0;
          args[i] = sets[i][0];
          carets[--i]++;
        }
        args[i] = sets[i][carets[i]];
        return true;
      }
    
      return {
        next: next,
        do: function (block, _context) {
          return block.apply(_context, args);
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given my previous questions about the the usage of AMPL. Are there any other
First off, I'm aware that there are many questions related to this, but none
I have an odd question that I have always thought about, but could never
Just want to know if there other optional wrapper framework available that generate client
I know you can look at the row.count or tables.count, but are there other
There are other posts that say you can create a control in windows forms
I'm pretty much positive about this, but just to be on the safe side:
I have some questions about the concept of static polymporhism I somethimes hear about;
There are already questions about the Perl+AJAX, like here , here or here and
There is a question I have been wondering about for ages and I was

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.