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

257
Visualizações
How to make a function as pure function using javascript and react?

i have data like below,

const arr_obj = [
    {
        id: '1',
        children: [],
        type: 'TYPE1',
    },
    {
        id: '2',
        children: [
            {
                id: '1',
                children: [
                    {
                        //some attributes
                    }
                ],
                type: 'MAIN',
            },
            {
                id: '2',
                children: [
                    {
                        //some attributes
                     }
                ],
                type: 'MAIN',
            },
            {
                id: '3',
                children: [
                    {
                        //some attributes
                    }
                ],
                type: 'MAIN',
            },
        ]
        type: 'TYPE2',
    },
    {
        id: '3',
        children: [
            {
                id: '4',
                children: [
                    {
                        //some attributes
                    }
                ],
                type: 'MAIN',
            },
            {
                id: '5',
                children: [
                    {
                        //some attributes
                    }
                ],
                type: 'MAIN',
            },
            {
                id: '6',
                children: [
                    {
                        //some attributes
                    }
                ],
                type: 'MAIN',
            },
        ]
        type: 'TYPE2',
    }
]

I have to find out the count of type: 'MAIN'. these 'MAIN' will be within type: "type2"

So the expected count is 6.

below is the code,

const ParentComponent = () => {
    const findCount = (arr_obj) => {
        let count = 0;
        const expectedCount = 2;
        const loop = (children) => {
            for (const obj of children) {
                const { type, children } = obj;
                if (type === 'TYPE2') {
                    loop(children);
                } else if (type === 'MAIN') {
                    ++count;
                    if (count > expectedCount) return;
                }
            }
        };
        loop(children);
        return count > expectedCount;
    };

    const output = findCount(arr_obj);

    return (
        //some jsx rendering
    );
 }

the above code works fine. but i want to make loop(children) function a pure function. I am not sure how to do it.

the problem now is i define variables outside the loop method. how can i define everything as arguments to the function, you could move the function outside the component.

could someone help me with this. thanks.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could take an array of the wanted type order and iterate only one level and han over the rest of wanted type. If no type are left over, return one otherwise the result of nested count.

const
    getCount = (array, types) => {
        let count = 0;
        for (const { type, children } of array) {
            if (types[0] === type) {
                count += types.length === 1
                    ? 1
                    : getCount(children, types.slice(1));
            }
        }
        return count;
    }
    data = [{ id: '1', children: [], type: 'TYPE1' }, { id: '2', children: [{ id: '1', children: [{}], type: 'MAIN' }, { id: '2', children: [{}], type: 'MAIN' }, { id: '3', children: [{} ], type: 'MAIN' }], type: 'TYPE2' }, { id: '3', children: [{ id: '4', children: [{}], type: 'MAIN' }, { id: '5', children: [{}], type: 'MAIN' }, { id: '6', children: [{}], type: 'MAIN' }], type: 'TYPE2' }],
    order = ['TYPE2', 'MAIN'],
    count = getCount(data, order);

console.log(count);

about 4 years ago · Juan Pablo Isaza Relatório

0

Pure Function is a function (a block of code ) that always returns the same result if the same arguments are passed. It does not depend on any state, or data change during a program’s execution rather it only depends on its input arguments.

Reference

In the above shared code I could see expectedCount as the shared variable which is not the PURE function.

As I could see your comments the desired type is in Children then its just the 2 levels. Then the following code would work.

function count(data, condition) {
    let count = 0;
    data.forEach((value, index) => {
    if(value.type === condition[0]){
        value.children.forEach((val, idx) => {
            if(val.type === condition[1]) {
            count++;
          }
        })
      }
    });
    return count;
}
const condition = ['TYPE2', 'MAIN'];
console.log(count(arr_obj, condition));
about 4 years ago · Juan Pablo Isaza Relatório

0

Nina's answer is more to the point but you could also do it by filtering the input array.

const data = [{ id: '1', children: [], type: 'TYPE1' }, { id: '2', children: [{ id: '1', children: [{}], type: 'MAIN' }, { id: '2', children: [{}], type: 'MAIN' }, { id: '3', children: [{} ], type: 'MAIN' }], type: 'TYPE2' }, { id: '3', children: [{ id: '4', children: [{}], type: 'MAIN' }, { id: '5', children: [{}], type: 'MAIN' }, { id: '6', children: [{}], type: 'MAIN' }], type: 'TYPE2' }];

const count = data
  .filter(v=>v.type==='TYPE2')
  .flatMap(v=>v.children)
  .filter(v=>v.type==='MAIN')
  .length

console.log(count);

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