let assume I have below list
1: Peter,
2: Mary,
3: Ken
...
I want to have a function switch
which return like below
let value1 = switch("Peter") // return 1
let value2 = switch(3) // return "Ken"
I know I can create a stupid function like
const switch = (input) => {
if(typeof(input) === string){...}
else if(typeof(input) === number){...}
}
Just want to know if there're any data structures which can help to do it better, instead of creating the objects for storing those pairs
CodePudding user response:
You can use Object.entries
for looking up the value and key at the same time
//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"
CodePudding user response:
Assuming the list is ordered, you can just convert it into an Array and use 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));