How to make a function as pure function using javascript and react?

Viewed 67

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.

3 Answers

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);

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));

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);

Related