Search code examples
javascriptreactjsformsecmascript-6ecmascript-5

return value from array index value based on input


I'm working on a reporting tool that I'm not sure how to build -

Basically, I am using a form, that takes the users input and converts it.

The overall structure of the object will look something like this...

object {
 userInput: ' ',
 available: ' ',
}

once the user has input some data, it should take the input and change into a different number.

silo_1Lookup = userInput => {
  silo_1DepthsFilling = [926, 893, 860, 827, 794, 761];
};

Conversion will be done in 1 function, and then updates the object.

pseudo code:

if (object.userInput === "0") {
  object.available = "926";
}

Each value will correspond with an index in that array, so if object.userInput === '2.5' then object.avaible will be 761 (arrayIndex: 6)


Solution

  • One way is using a dictionary to map userInput to available value, something like:

    const USER_MAPPING = {
      "0": "926",
      "3": "5412",
      "2": "2321"
      // ... rest values
    };
    
    // usage
    return USER_MAPPING[object.userInput];
    

    Such mapping is hard-coded and opens opportunities for bugs, so if there is any logic behind userInput and the values, you should generate some function for it:

    return generateAvailable(object.userInput)