Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda