Skip to content
Advertisement

How I can reset variable value when function end?

I have such function and global variable (as array):

const arraysList = []

export const changeColorCategories = (array, draggedColumnId) => {
    const isColor = arraysList.length ? arraysList[0][0]?.color : [];

    if (typeof isColor === 'string') {
        firstLevelColor = isColor;
    }

    return array.map((item, index, categories) => {
        item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
        arraysList.push(categories);
        
        if (firstLevelColor && !draggedColumnId) {
            item.color = firstLevelColor;
        }

        if (item?.children?.length) {
            changeColorCategories(item.children);
        }
        
        return item;
    })
} 

Every call of this function push some data to array. In this function I use recursion. So how i can clear this array only when this function will end it’s work.

Answer

You can call the recursion function inside another function this way you can run anything you want when the function ends

const arraysList = []

export const changeColorCategories = (array, draggedColumnId) => {
    const isColor = arraysList.length ? arraysList[0][0]?.color : [];

    if (typeof isColor === 'string') {
        firstLevelColor = isColor;
    }

    return array.map((item, index, categories) => {
        item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
        arraysList.push(categories);
        
        if (firstLevelColor && !draggedColumnId) {
            item.color = firstLevelColor;
        }

        if (item?.children?.length) {
            changeColorCategories(item.children);
        }
        
        return item;
    })
} 

function runRucFunc(){
    const result = changeColorCategories();
    //Your other code goes here

    return result;
}
Advertisement