Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: How to populate arguments passed to a function?

I have this code that returns cartesian product of three arrays:

function getcartesianProduct(symbols: Array<string>) {
  const cartesian = <T,>(...sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]);
  return cartesian(symbols, symbols, symbols).map((items: Array<string>) => items.join(""));
}

For example, like this:

>> const numbers: Array<string> = "0123456789".split("");
>> getcartesianProduct(numbers).slice(0, 5)
["000", "001", "002", "003", "004"]

However, I don’t always want my number series to be made out of three numbers. Sometimes, I want four, five, or any other number. That is why I would like to have an argument that would populate the arguments inside cartesian() function call, accordingly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would imagine something like this:

function getcartesianProduct(symbols: Array<string>, n: number) {
  const cartesian = <T,>(...sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]);
  return cartesian(symbols * 3).map((items: Array<string>) => items.join(""));
}

How can I do that, please? Every help is appreciated.

>Solution :

I think something like this should work:

function getcartesianProduct(symbols: string[], nrOfArrays: number) {
  const cartesian = <T,>(sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]);
  return cartesian<string>(new Array(nrOfArrays).fill(symbols)).map((items: string[]) => items.join("")).slice(0, nrOfArrays);
}

const numbers = "0123456789".split("");
console.log(getcartesianProduct(numbers, 5))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading