What is the process of calculating the cartesian product using TypeScript?

My desired type signature is as follows:

function cartesianProduct<T1, T2, T3, T4, T5, T6, T7, T8>([c1, c2, c3, c4, c5, c6, c7, c8]: [T1[], T2[], T3[], T4[], T5[], T6[], T7[], T8[]]): [T1, T2, T3, T4, T5, T6, T7, T8][];
function cartesianProduct<T1, T2, T3, T4, T5, T6, T7>([c1, c2, c3, c4, c5, c6, c7]: [T1[], T2[], T3[], T4[], T5[], T6[], T7[]]): [T1, T2, T3, T4, T5, T6, T7][];
function cartesianProduct<T1, T2, T3, T4, T5, T6>([c1, c2, c3, c4, c5, c6]: [T1[], T2[], T3[], T4[], T5[], T6[]]): [T1, T2, T3, T4, T5, T6][];
function cartesianProduct<T1, T2, T3, T4, T5>([c1, c2, c3, c4, c5]: [T1[], T2[], T3[], T4[], T5]): [T1, T2, T3, T4, T5][];
function cartesianProduct<T1, T2, T3, T4>([c1, c2, c3, c4]: [T1[], T2[], T3[], T4[]]): [T1, T2, T3, T4][];
function cartesianProduct<T1, T2, T3>([c1, c2, c3]: [T1[], T2[], T3[]]): [T1, T2, T3][];
function cartesianProduct<T1, T2>([c1, c2]: [T1[], T2[]]): [T1, T2][];
function cartesianProduct<T>(sets: T[][]): T[][] {
  // implementation
}

For example, with the input:

const input = [
  [ 'a', 'b' ],
  [ 1, 2 ],
];

The expected output would be:

const output = [
  [ 'a', 1 ],
  [ 'a', 2 ],
  [ 'b', 1 ],
  [ 'b', 2 ],
];

Attempting to use this reference implementation results in a type problem:

https://i.sstatic.net/CRJGX.png

Here's a link to the TypeScript playground for reference.

Answer №1

If you're interested in leveraging Ramda, consider utilizing R.sequence specifically with arrays.

const combine = R.sequence(Array.of)

const data = [
  [ 'x', 'y' ],
  [ 3, 4 ]
];

combine(data)
//=> [["x", 3], ["x", 4], ["y", 3], ["y", 4]]

Answer №2

When approaching problems like this, my go-to is always to begin by identifying the types involved.

Firstly, a type is defined to extract the element type of an array:

type ElementType<A> = A extends ReadonlyArray<infer T> ? T : never;

Although A[number] exists, using this will lead to type errors later on due to the nature of A being a result from infer.

Next, a type is created that takes a list of arrays and provides their respective element types:

type ElementsOfAll<Inputs, R extends ReadonlyArray<unknown> = []> = Inputs extends readonly [infer F, ...infer M] ? ElementsOfAll<M, [...R, ElementType<F>]> : R;

This is akin to

Inputs.map((F) => ElementType(F))
in actual code.

Finally, utilizing the aforementioned types, a CartesianProduct type is established:

type CartesianProduct<Inputs> = ElementsOfAll<Inputs>[];

Now, having laid out the groundwork with types, it's time to translate this into executable code:

function cartesianProduct(sets) {
  return sets.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
}

The impeccable implementation presented here was sourced from this fantastic answer, which also offers alternative solutions if your environment does not support flat or flatMap.

Once we have implemented the function, we then add the types:

function cartesianProduct<Sets extends ReadonlyArray<ReadonlyArray<unknown>>>(sets: Sets): CartesianProduct<Sets> {
  return sets.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
}

However, an error arises because the return type does not align with the type expected by the reduce function. Unfortunately, I do not know an elegant solution to eliminate this error, but if a cast is acceptable:

function cartesianProduct<Sets extends ReadonlyArray<ReadonlyArray<unknown>>>(sets: Sets): CartesianProduct<Sets> {
  return sets.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat()))) as CartesianProduct<Sets>;
}

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to extract information from paginated asp pages using Scrapy Splash in the Python programming language

I am currently working on a project that involves using scrapy and splash to extract information such as Staff, job titles, and emails from a specific website's staff page. Here is the link to the page: . Due to the presence of dynamic javascript code ...

Tips for implementing a reusable instance of a class in (SSR) React (comparable to a @Bean in Spring)

I am currently developing a new application using Next.js and React (Server Components) in TypeScript. In order to showcase and evaluate the app, I need to support two different data sources that provide identical data through separate APIs. My goal is to ...

Transitioning effects for Carousel in Bootstrap 4 Beta using Fade technique

I am attempting to customize the new Beta version of Bootstrap 4 Carousel to transition between slides with a fade effect instead of sliding, using CSS. Unfortunately, I have been unsuccessful in getting it to work. I'm unsure if a specific Javascript ...

Laravel is displaying an error message stating "undefined index:year" despite the fact that the field is

When filling out a registration form, there is a select category that allows you to hide or display specific input fields based on the category selected. For instance, choosing "student" will reveal hidden input fields for year and section. However, if "fa ...

Showing the current HTML page using JavaScript when clicking?

Currently, I am working on changing the page layout using JavaScript when a function is triggered by clicking. My question is, how can I make the JavaScript display the current HTML body? The process is as follows: First, there is the page's HTML an ...

Error encountered when making Ajax request to WCF service: receiving an Object object

I am dealing with a WCF method that returns JSON data: view image description here The client has a script that needs to fetch the data from the WCF service. Here is the script: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.j ...

What is the best way to showcase JSON data while incorporating HTML tags in a React application?

My JSON data contains HTML tags interspersed within it and I have successfully fetched and displayed the data. See the code snippet below: componentDidMount() { this._callCake(); } _renderEachCake = () => { return ( <EachCake ...

Making a surface-level copy of an array containing nested arrays

I am facing an issue with manipulating child arrays within a parent array. Specifically, I want to manipulate the first element in the first child array without affecting the rest of the arrays. However, my current code is shifting the first elements of al ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

The json.stringify method is inserting additional backslashes into the response sent by res.send()

My API needs to provide the following data in its response. { users: 'All users are as follows: [{id: 1}, {id: 2}]'} The response should be a JSON object with one key value being a JSON array. However, the JSON array is converted into a string b ...

What are the steps for implementing Babel in a CLI program?

Currently, I am working on developing a CLI program in Node using Babel. While researching, I came across a question on Stack Overflow where user loganfsmyth recommended: Ideally you'd precompile before distributing your package. Following this ad ...

Organizing menu options into subcategories using jQuery UI for easy sorting

I am currently working on a horizontal jQuery menu item that includes the sortable option and has one submenu. My goals for this project are as follows: To keep the menu item with the submenu locked at the end of the list To be able to drag menu items fr ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

The checkbox function is malfunctioning when integrated with JavaScript

I am facing an issue with my HTML checkbox that is supposed to select all checkboxes after clicking, but it doesn't seem to be working correctly. What could be causing this problem? Here is the JavaScript code I am using: <script language="JavaSc ...

What is the best way to develop interactive components using Google App Scripts for Google Sites?

I am currently working on building dynamic app script components that can be seamlessly integrated into my website, each with unique data for every instance of the script. I initially attempted using parameters but I'm uncertain if this is the most ef ...

struggling to set dropdown select value within an AngularJS controller

I'm feeling a bit puzzled about the issue I am experiencing. Let me explain. HTML <div> <select ng-model="params.select" ng-change="View($event)"> <option value="" disabled>-</option> <option val ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

Having difficulty capturing an error related to an invalid form body in discord.js

I built a command to send an embed based on JSON data, and it's working well for the most part. When I input the data correctly, the bot sends it to the channel as expected. However, if someone tries to insert text in a link section, it crashes the b ...

transferring information back and forth between a javascript array and php

Currently, I am developing a design website that allows users to create designs on an HTML5 canvas and save them on the server. All user information is stored in a MySQL database, while the designs are saved in a JavaScript array. My goal is to seamlessly ...