Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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.

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!