In the below code I am trying to make a switch statement that takes in the following inputs: 34, ’34’, {input: 34}, hello, [“hello”]
and returns the number 34 within each input, the cases I need to have are:
JavaScript
x
5
1
If given a number, return the number
2
If given a string, convert it to a number and return the result
3
If given an object, return the value of the input property
4
Otherwise, throw an error: "Unexpected data type"
5
I am having an issue with the object input. Thank you so much!
JavaScript
1
16
16
1
function parseNumber(unknown) {
2
switch(unknown) {
3
case 34:
4
return unknown;
5
6
case '34':
7
return parseInt(unknown);
8
9
case unknown.input:
10
return unknown.input;
11
12
default:
13
throw new Error("Unexpected data type");
14
}
15
}
16
Advertisement
Answer
You can use typeof
result in the switch cases, to determine the output:
JavaScript
1
50
50
1
/*If given a number, return the number
2
If given a string, convert it to a number and return the result
3
If given an object, return the value of the input property
4
Otherwise, throw an error: "Unexpected data type"*/
5
6
7
function parseNumber(unknown) {
8
const type = typeof unknown;
9
//typeof null is object so throwing error
10
if (!unknown) throw new Error("Unexpected data type");
11
//for non numeric strings throwing error
12
if (type === "string" && Object.is(+unknown, NaN)) throw new Error("Unexpected data type");
13
//typeof Array is object so excluding arrays
14
if (Array.isArray(unknown)) throw new Error("Unexpected data type");
15
if (type === "object" && !unknown.hasOwnProperty("input")) throw new Error("Unexpected data type");
16
17
switch (type) {
18
case "number":
19
return unknown;
20
case "string":
21
return +unknown;
22
case "object":
23
return unknown.input;
24
default:
25
throw new Error("Unexpected data type");
26
}
27
}
28
console.log(parseNumber(34));
29
console.log(parseNumber('34'));
30
console.log(parseNumber({input: 34}));
31
//Error cases
32
try{
33
console.log(parseNumber("hello"));
34
}catch(e){console.error(e)}
35
36
try{
37
console.log(parseNumber());
38
}catch(e){console.error(e)}
39
40
try{
41
console.log(parseNumber(() => "hello"));
42
}catch(e){console.error(e)}
43
44
try{
45
console.log(parseNumber([34]));
46
}catch(e){console.error(e)}
47
48
try{
49
console.log(parseNumber({"foo": "bar"}));
50
}catch(e){console.error(e)}