Estoy tratando de descubrir cómo convertir la siguiente función de javascript en una función dinámica que realizará el flapMap recursivamente.
function getPermutations(object) { let array1 = object[0].options, array2 = object[1].options, array3 = object[2].options; return array1.flatMap(function(array1_item) { return array2.flatMap(function(array2_item) { return array3.flatMap(function(array3_item) { return array1_item + ' ' + array2_item + ' ' + array3_item; }); }); }); } let object = [{ "options": ['blue', 'gray', 'green'] }, { "options": ['large', 'medium', 'small'] }, { "options": ['wood', 'steel', 'pastic'] }]; console.log('Permutations', getPermutations(object));En el ejemplo, envío 3 matrices a la función, por lo que tiene 3 iteraciones de flapMap. Funciona bien, pero estoy tratando de hacerlo dinámico, por lo que puedo pasar una matriz dinámica y la función haría el flapMap recursivamente según la matriz.
En su ejemplo, realizó un seguimiento de array1_item , array2_item y co en sus variables individuales. Puede moverlos a una matriz (que tenga un tamaño dinámico; lo llamé _prevItems ) y pasarlos como un parámetro a la llamada recursiva.
function getPermutations(objects, _prevItems = []) { // join the items at the end of the recursion if (objects.length === 0) return _prevItems.join(' ') // call again with all but the first element, and add the current item to _prevItems return objects[0].flatMap(item => getPermutations(objects.slice(1), [..._prevItems, item])) } let objects = [['blue', 'gray', 'green'], ['large', 'medium', 'small'], ['wood', 'steel', 'pastic']]; console.log('Permutations', getPermutations(objects));Una forma de hacerlo es con reduce .
Desea reducir la lista de opciones a una lista de permutaciones.
function getPermutations(list) { return ( list // First map to list of options (list of list of strings) .map((item) => item.options) // Then reduce. Do not set any initial value. // Then the initial value will be the first list of options (in // our example, ["blue", "gray", "green"]) .reduce((permutations, options) => { return permutations.flatMap((permutation) => options.map((option) => permutation + " " + option) ); }) ); } // Renamed this to list, since it is an array and not an object const list = [ { options: ["blue", "gray", "green"] }, { options: ["large", "medium", "small"] }, { options: ["wood", "steel", "pastic"] }, ]; console.log("Permutations", getPermutations(list));Editar: Sé que pediste recursividad. Si se trata de una tarea de la escuela, quizás deba usar la recursividad, pero de lo contrario recomendaría evitar la recursividad cuando sea posible, ya que tiende a complicar las cosas. (Por supuesto, esta es una regla general y, como todas las reglas, tiene algunas excepciones).
puede crear un mapa plano de dos matrices a la vez utilizando el enfoque recursivo de abajo hacia arriba y construir su cadena desde el final
const getPermutations = (array) => { if(array.length === 1) return array[0].options; const prefixItems = array[0].options; const suffixItems = getPermutations(array.slice(1)); return prefixItems.flatMap(prefix => { return suffixItems.flatMap(suffix => { return prefix + ' ' + suffix }); }) }