supongamos que tengo la siguiente lista
1: Peter, 2: Mary, 3: Ken ... Quiero tener un switch de función que regrese como a continuación
let value1 = switch("Peter") // return 1 let value2 = switch(3) // return "Ken"Sé que puedo crear una función estúpida como
const switch = (input) => { if(typeof(input) === string){...} else if(typeof(input) === number){...} }Solo quiero saber si hay alguna estructura de datos que pueda ayudar a hacerlo mejor, en lugar de crear los objetos para almacenar esos pares.
Puede usar Object.entries para buscar el valor y la clave al mismo tiempo
//cannot assign numbers as keys directly const data = { "1": "Peter", "2": "Mary", "3": "Ken" }; //`switch` is a programming language key for `switch/case` //so I name the function `switchDataInPair` instead of `switch` function switchDataInPair(input) { for (const [key, value] of Object.entries(data)) { //cannot use absolute check with `===`, because numbers are strings if (key == input) { return value } if (value == input) { return key } } return "Not defined" } console.log(switchDataInPair("Ken")) //3 console.log(switchDataInPair(1)) //"Peter" console.log(switchDataInPair("Something")) //"Not defined"Suponiendo que la lista esté ordenada, puede convertirla en una matriz y usar indexOf
const arr= ["Peter","Mary", "Ken"]; /*Switch is a keyword in javascript, so best use a different variable name.*/ const switcher= (input) => { if(typeof(input) === "string") { const result= arr.indexOf(input); return ~result ? result : "not found"; //above line is equivalent to result > -1 ? result : "not found" } else if(typeof(input) === "number") { return arr[input] } } console.log(switcher("Mary")); console.log(switcher(1));