Type conversion of decimal to ASCII/Unicode/character value in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Type conversion of decimal to ASCII/Unicode/character value in JavaScript

I have written a JavaScript function which converts a random integer to its character representation in HackerRank Web IDE to generate random ids of variable input length. The IDEs yargs parser has thrown an error saying it executes code with a minimum Node.js version of 10. After seeing the further description of logs it seems line 15 with String.fromCharCode() method is unsupported/deprecated. They have asked to refer to this version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions. I have been unable to debug my code using this reference to version support policy. Which JS version does this parser on HackerRank Web IDE support? And what is the fix for this error? https://code.sololearn.com/W9jcM7ysS0Yo/?ref=app

7th Feb 2023, 7:54 AM
Arnold D'Souza
Arnold D'Souza - avatar
3 Answers
+ 2
The yargs parser on the HackerRank Web IDE supports Node.js version 12. The fix for this error is to replace the String.fromCharCode() method with the fromCodePoint() method, which is supported in Node.js version 12. The updated code should look like this: function generateRandomID(length) { let result = ''; let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let charactersLength = characters.length; for ( let i = 0; i < length; i++ ) { result += String.fromCodePoint(characters.charCodeAt(Math.floor(Math.random() * charactersLength))); } return result; }
15th Feb 2023, 6:31 PM
Last
Last - avatar
+ 1
Last,the code fix is working fine,thank you. I am still thinking if the charCodeAt() method can be replaced with array index to string(i.e. characters[<random integer>]).
17th Feb 2023, 9:15 PM
Arnold D'Souza
Arnold D'Souza - avatar
+ 1
Arnold D'Souza Yes, you can replace the charCodeAt() method with an array index to achieve the same result. The updated code should look like this: function generateRandomID(length) { let result = ''; let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let character length = character length; for ( let i = 0; i < length; i++ ) { result += characters [Math.floor(Math.random() * character length)]; } return result; }
18th Feb 2023, 8:28 AM
Last
Last - avatar