[SOLVED] Custom JavaScript method to convert any datatype to Boolean | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[SOLVED] Custom JavaScript method to convert any datatype to Boolean

I need a method to convert the data given by the user into Boolean. The input comes in the form of numbers, number inside quotes and string. Eg: => 0, 1, 2 (just for testing the method) => "0", "1", "2" (this is important) => "true", "false", "hello" (just for testing the method) Result pattern: "true", "false", "hello", "1", "2", 1, 2 => true "0", 0 => false But I'm missing something in my my code which giving unexpected output. Help me to solve it. https://code.sololearn.com/Wv3i2kbejIjo

22nd Nov 2020, 10:47 AM
Bibek Oli
Bibek Oli - avatar
1 Answer
+ 4
When you go with `typeof this` inside an object prototype, `this` refers to the object itself rather than its underlying value. For this reason `typeof this` inside an object prototype gives `object`. A web search showed me that we'd need to get object.constructor.name instead (it's a string). We can afterwards convert the string to lowercase and pass it into a `switch` for comparison. Object.prototype.bool = function() { let typeID = this.constructor.name.toLowerCase(); switch(typeID) { case "number": return Boolean(this != 0); case "string": if(!this.length) return false; if(this == "false") return false; let value = Number(this); if(!isNaN(value)) return (value != 0); return true; default: return Boolean(this); } }
22nd Nov 2020, 2:57 PM
Ipang