Recursively change a tree isDisable boolean


Given a tree:

type DataType = {
  id: string;
  access: 'view' | 'none';
  isDisabled: boolean;
  children: DataType[];
};

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: [],
    },
  ],
};

What I want to do is when a node’s access changes, the isDisabled boolean will change based on the following rules:

If access is ‘view’, the isDisabled will remain false
If access is ‘none’, the isDisabled in the current node will be false, but it’s children’s isDisabled will be true.

This is what I have now:

export const find = (data, selectedId, access) => {
  if (!selectedId || !access) {
    return data;
  }

  if (data.id === selectedId) {
    data = changeAccess(data, selectedId, access);
    return data;
  }
  data.children.map((child) => find(child, selectedId, access));

  return data; // this is where the problem lies, but not sure how to fix it
};

export const changeAccess = (data, selectedId, access) => ({
  ...data,
  access: access,
  isDisabled: data.dataId !== selectedId && access !== 'view' ? true : false, // this toggles isDisabled
  children: data.children?.map((child) =>
    changeAccess(child, selectedId, access)
  ),
});

So when I call ‘find’

const result = find(Data, '2', 'none');

result should equal the below:

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: 'none',
          isDisabled: true,
          children: [],
        },
      ],
    },
    {
      id: '5',
      access: 'view',
      isDisabled: false,
      children: [],
    },
  ],
};

P.S. I already have a function that mutates the original array, but what I need is for it to return the data instead.

Source: JavaSript – Stack Overflow

August 23, 2021
Category : News
Tags: javascript | recursion | tree | treeview | typescript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.