Home > OS >  How to solve a JS logic problem where some values have to increment based on a previous value keepin
How to solve a JS logic problem where some values have to increment based on a previous value keepin

Time:10-12

I'm trying to solve a problem I have in my JS which is related to the following snippet

const signatureOrder = role => {
  let order;
  switch (role) {
    case 'GUARDIAN':
      order = 2;
      break;
    case 'ASSENTEE':
      order = 3;
      break;
    case 'COUNTERSIGNEE':
      order = 4;
      break;
    default:
      order = 1;
      break;
  }

  return order;
};

This method basically takes a role which currently is 4: CONSENTEE, GUARDIAN, ASSENTEE, COUNTERSIGNEE.

The CONSENTEE is always 1 and the order is always as the numbers from 1 to 5.

However, there can be a situation where I can have like multi roles coming:

1 consented 
2 guardians
2 assentee
1 countersignee

This will be translated by the method in the following order

1 consented
2 Guardian
2 Guardian
3 Assentee
3 Assentee 
4 Countersignee 

This is not very correct and the output should be an increment of the single values but keeping the order fixed as below:

1 Consented
2 Guardian
3 Guardian
4 Assentee
5 Assentee
6 Countersignee

so what happens is that if we have already a guardian the next guardian becomes the previous guardian 1 but stays always after Consentee and before Assentee.

The scenarios areas:

  • consentee is the one always be there is always 1
  • Always we have 4 roles
  • but we can have different combinations like no guardians, no assentee, yes countersigned and so on
  • The always present role is consentee the other roles are present or not depending of the situation
  • We can have already a list of this roles and adding again guardian should change the values for example we have C 1, G 2, A 3 and we add G so will change 1 everywhere so will have c1, G 2, G 3, A 4 ...

I would like to understand how to solve this in the right manner.

CodePudding user response:

You can sort all your elements based on an orderArray. Then, assign the order based on the element index.

Based on this answer:

const orderArray = ['CONSENTEE', 'GUARDIAN', 'ASSENTEE', 'COUNTERSIGNEE']

const elements = ['CONSENTEE', 'ASSENTEE', 'GUARDIAN', 'COUNTERSIGNEE', 'ASSENTEE',  'GUARDIAN']

elements.sort(function(a, b){  
  return orderArray.indexOf(a) - orderArray.indexOf(b);
});

const withOrder = elements.map((el, i) => { 
  return {role: el, order: i 1}
})
console.log(withOrder)

CodePudding user response:

It seems to me you need something like this:

const sortRoles = rolesArray => {
    const orderOfRole = {
        'CONSENTED': 1,
        'GUARDIAN': 2,
        'ASSENTEE': 3,
        'COUNTERSIGNEE': 4
    }
    rolesArray.sort((role1, role2) => orderOfRole[role1] - orderOfRole[role2])
}

where, in the end, the order is just the index in the sorted array, incremented by 1.

  • Related