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:
If given a number, return the number If given a string, convert it to a number and return the result If given an object, return the value of the input property Otherwise, throw an error: "Unexpected data type"
I am having an issue with the object input. Thank you so much!
function parseNumber(unknown) { switch(unknown) { case 34: return unknown; case '34': return parseInt(unknown); case unknown.input: return unknown.input; default: throw new Error("Unexpected data type"); } }
Advertisement
Answer
You can use typeof
result in the switch cases, to determine the output:
/*If given a number, return the number If given a string, convert it to a number and return the result If given an object, return the value of the input property Otherwise, throw an error: "Unexpected data type"*/ function parseNumber(unknown) { const type = typeof unknown; //typeof null is object so throwing error if (!unknown) throw new Error("Unexpected data type"); //for non numeric strings throwing error if (type === "string" && Object.is(+unknown, NaN)) throw new Error("Unexpected data type"); //typeof Array is object so excluding arrays if (Array.isArray(unknown)) throw new Error("Unexpected data type"); if (type === "object" && !unknown.hasOwnProperty("input")) throw new Error("Unexpected data type"); switch (type) { case "number": return unknown; case "string": return +unknown; case "object": return unknown.input; default: throw new Error("Unexpected data type"); } } console.log(parseNumber(34)); console.log(parseNumber('34')); console.log(parseNumber({input: 34})); //Error cases try{ console.log(parseNumber("hello")); }catch(e){console.error(e)} try{ console.log(parseNumber()); }catch(e){console.error(e)} try{ console.log(parseNumber(() => "hello")); }catch(e){console.error(e)} try{ console.log(parseNumber([34])); }catch(e){console.error(e)} try{ console.log(parseNumber({"foo": "bar"})); }catch(e){console.error(e)}