Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Key Value Pairs in Javascript

I have a Business Scenario as below.

I am adding rows of possible (key, value) pairs.(Country, Climate) like one below.

In Image 2 the whole scenario Valid and Invalid (Key, Value) are given.


Possible Keys - All Country, India, Australia, America, England

Possible Values - All Climate, Hot, Dry, Rainy, Cold, Humid


For Example

if (All Country, All Climate) is chosen as first pair (England, hot) should not be allowed to be chosen as second pair

If (All Country, hot) is chosen as first pair (India, hot) should not be allowed to bechosen as second pair

If (America, All Climate) is chosen as first pair (America, Hot) should not be allowed to be chosen as second pair

where as

If (India, hot) is chosen as first pair (India, humid) shall be allowed chosen as second pair

If (America, All Climate) is chosen as first pair (England, All Climate) shall be be allowed chosen as second pair

If (America, All Climate) is chosen as first pair (India, humid) shall be allowed to be chosen as second pair

Image 1

Image1


Image 2

Image2

Question I have explained My Colleague all the valid and Invalid possible combinations through the Image2.

In javascript the simplest solution would be to add if else statements and getting it done.By doing so the gap between the one I explained to solve Business Scenario in paper and code widens.

What would be the best implementation of transferring the Matrix in the Paper to Code so the business in the paper and code have a close relation.

This question may sound vague but we all at least once faced issue like this where things written to solve a problem in paper and the way it solved by code makes no sense.

like image 927
ArrayOutOfBound Avatar asked Nov 09 '22 12:11

ArrayOutOfBound


1 Answers

Use binary arithmetic.

Country values

India       0001
Australia   0010
America     0100
England     1000
All Country 1111

Climate Value

Hot         00001
Dry         00010
Rainy       00100
Cold        01000
Humid       10000
All Climate 11111

When you choose second item, use AND operation to decide if that value is already choosen, (ALL or same value).

example

var firstCountry = 0xF
var secondCountry = 0x1
if ( (firstCountry & secondCountry) > 0)
{
    console.log("country is already choosen");
}

Of course this example is only for one attribute. You should update it for both attributes.

like image 107
Atilla Ozgur Avatar answered Nov 14 '22 22:11

Atilla Ozgur