Looking at the tree data structure I have:
type DataType = {
id: string;
access: 'view' | 'none';
isDisabled: boolean;
children: DataType[];
};
export const Data: DataType = {
id: '1',
access: 'view',
isDisabled: false,
children: [
{
id: '2',
access: 'view',
isDisabled: false,
children: [
{
id: '3',
access: 'view',
isDisabled: false,
children: [],
},
],
},
{
id: '4',
access: 'view',
isDisabled: false,
children: [],
},
{
id: '5',
access: 'view',
isDisabled: false,
children: [],
},
],
};
The goal is to update the isDisabled property when a node's access changes according to specific rules:
If access is set to 'view', then isDisabled remains false. If access is set to 'none', then isDisabled will be false for the current node but true for its children.
There are two functions available, however they are not functioning as intended:
// Function to find the desired node
const find = (
data: DataType,
selectedId: string,
selectedAccess: 'view' | 'none'
) => {
if (selectedId && selectedAccess) {
if (data.id === selectedId) {
data = changeAccess(data, selectedId, selectedAccess);
} else {
data.children.forEach((child) => find(child, selectedId, selectedAccess));
}
}
};
// Function to update access and isDisabled properties
const changeAccess = (
data: DataType,
selectedId: string,
selectedAccess: 'view' | 'none'
): DataType => ({
id: data.id,
access: selectedAccess,
isDisabled:
data.id !== selectedId && selectedAccess !== 'view' ? true : false,
children: data.children?.map((child) =>
changeAccess(child, selectedId, selectedAccess)
),
});
When calling the find function with:
find(Data, '2', 'none');
The resulting updated data would be:
const DataAfter: DataType = {
id: '1',
access: 'view',
isDisabled: false,
children: [
{
id: '2',
access: 'none',
isDisabled: false,
children: [
{
id: '3',
access: 'none',
isDisabled: true,
children: [],
},
],
},
{
id: '4',
access: 'view',
isDisabled: false,
children: [
{
id: '5',
access: 'view',
isDisabled: false,
children: [],
},
],
},
],
};
Subsequent calls to find would further update the tree structure accordingly based on the provided rules.
If there are any insights or suggestions on how to improve these functions, it would be greatly appreciated.
I am still learning about recursion and tree data structures, and looking to enhance my understanding through practical exercises like this one.