Home > front end >  How to rebuild condition with associative array to enum
How to rebuild condition with associative array to enum

Time:04-09

Hello guys is have a condition and its works, but I need rebuild it to enum and enum does not work with my old condition. p.s. teamlead said

  1. My working case is:
        const basketAccepts = {
        0: ['Values'],
        1: ['Rows', 'Columns']
      }

const basketAcceptValues = isOver && visualType === 'matrix' && !basketAccepts[Number(!dragItem.Measure)].includes(basketName)

When I hover some div some css things are happening

  • basketName - string (Values, Rows, Columns) can be all or one depend of visualType
  • dragItem.Measure = boolean

So I need it rebuild for same case but for enum.

enum basketAccepts {
'Values' = 0,
'Rows' = 1,
'Columns' = 1,

}

CodePudding user response:

I used the ternary operator to decide the value of each enum property as if it's cointained or not at index zero of basketAccepts being one or zero respectively. So this logic assumes that all those 3 conditions will appear on the other set [1] if they are not contained in the first one.

I actually couldn't verify it because I'm not used to TypeScript. Please let me know if it worked.

const basketAccepts = {
    0: ['Values'],
    1: ['Rows', 'Columns']
};

enum basketAccepts {
  //use value 0 if 'Values' appears in basketAccepts[0] otherwise 1
  'Values' = basketAccepts[0].includes('Values') ? 0 : 1,
  //use value 0 if 'Rows' appears in basketAccepts[0] otherwise 1
  'Rows' = basketAccepts[0].includes('Rows') ? 0 : 1,
  //use value 0 if 'Columns' appears in basketAccepts[0] otherwise 1
  'Columns' = basketAccepts[0].includes('Columns') ? 0 : 1
}

console.log(basketAccepts);

CodePudding user response:

Not sure why your after using enums, enums in TS are none standard, and were implemented before the Dev's decided to strictly follow ES proposals, so personally I would avoid them.

But if you must still use them then this might help.

If you look at what TS converts your enum into ->

{
  "0": "Values",
  "1": "Columns",
  "Values": 0,
  "Rows": 1,
  "Columns": 1
} 

What we could do then is use Object.entries and Array.some.

eg..

enum basketAccepts {
  'Values' = 0,
  'Rows' = 1,
  'Columns' = 1,
}

const basketName = 'Rows';
const measure = true;

console.log(
   Object.entries(basketAccepts).
      some(([k,v ]) => 
         k == basketName && Boolean(v) == measure)
);

CodePudding user response:

Thanks guys for help, any way I remade it in a bit other way. Hope it help to some one.

export enum FieldType {
  Dimension,
  Measure
}

 const fieldCompatibilities = {
    [FieldType.Dimension]: ['Columns', 'Rows'],
    [FieldType.Measure]: ['Values']
 }

const basketAcceptValues = isOver && visualType === 'matrix' && !fieldCompatibilities[Number(dragItem.Measure)].includes(basketName)
  • Related